简体   繁体   中英

Error: invalid subscript type 'list' in R

Having an issue here - I'm creating a function using the eclipse parameter to deal with a varying function parameters. I recreated as similar situation to show the issue I keep bumping into,

> d <- data.frame(alpha=1:3, beta=4:6, gamma=7:9)
> d
  alpha beta gamma
1     1    4     7
2     2    5     8
3     3    6     9

> x <- list("alpha", "beta")
> rowSums(d[,c(x)])
Error in .subset(x, j) : invalid subscript type 'list'

How do I deal with the issue of feeding a list into a subset call?

We need to use concatenate to create a vector instead of list

x <- c("alpha", "beta")
rowSums(d[x])
#[1] 5 7 9

and if we are using list , then unlist it to create a vector as data.frame takes a vector of column names (column index) or row names (row index) to subset the columns or rows

x <- list("alpha", "beta")
rowSums(d[unlist(x)])
#[1] 5 7 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM