Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Error: invalid subscript type 'list' in R

Writer Matthew Harrington

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?

1 Answer

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
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy