Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: invalid subscript type 'list' in R

Tags:

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?

like image 733
S31 Avatar asked May 08 '17 03:05

S31


1 Answers

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
like image 200
akrun Avatar answered Nov 10 '22 03:11

akrun