开发者

loop over columns with semi like columnnames

I have the following variable and dataframe

welltypes <- c("LC","HC")
qccast <- data.frame(
  LC_mean=1:10,
  HC_mean=10:1,
  BC_mean=rep(0,10)
)

Now I only want to see the welltypes I selected(in this case LC and HC, but it could also be different ones.)

for(i in 1:length(welltypes)){
qccast$开发者_如何学编程welltypes[i]_mean
}

This does not work, I know. But how do i loop over those columns?

And it has to happen variable wise, because welltypes is of an unkown size.


The second argument to $ needs to be a column name of the first argument. I haven't run the code, but I would expect welltypes[i]_mean to be a syntax error. $ is similar to [[, so you can use paste to create the column name string and subset via [[.

For example:

qccast[[paste(welltypes[i],"_mean",sep="")]]

Depending on the rest of your code, you may be able to do something like this instead.

for(i in paste(welltypes,"_mean",sep="")){
  qccast[[i]]
}


Here's another strategy:

qccast[ sapply(welltypes, grep, names(qccast)) ]
   LC_mean HC_mean
1        1      10
2        2       9
3        3       8
4        4       7
5        5       6
6        6       5
7        7       4
8        8       3
9        9       2
10      10       1


Another easy way to access given welltypes

qccast[,paste(welltypes, '_mean', sep = "")]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜