invalid subscript type 'list' ERROR

Hi

I have the following data frames but could not solve this error :

>data

      id          rate
      101         13.2
      102         15.3
      103         16.3
      104         19.1
       ..         ..
       ..         .. 



>people2 

       id       class
      101         2
      102         2
      103         3
      104         1
       ..         ..
       ..         .. 

data$id <- as.character(data$id)


when I run this command:

data$group2 <- factor(people2$class[sapply(data$id, function(x) which(people2$id==x))])

it gives this error msg:

Error in people2$class[sapply(tstlcm$id, function(x) which(people2$id ==  : 
  invalid subscript type 'list'

I do not get an error with this slightly modified version of your code. All I did, I think, is change the name of one data frame from data to d, which should not make a difference.
It might be easier to use the merge function, as shown.

D <- data.frame(id = 101:104, rate = c(13.2, 15.3, 16.3, 19.1))
D
#>    id rate
#> 1 101 13.2
#> 2 102 15.3
#> 3 103 16.3
#> 4 104 19.1
people2 <- data.frame(id = 101:104, class = c(2,2,3,1))
people2
#>    id class
#> 1 101     2
#> 2 102     2
#> 3 103     3
#> 4 104     1
D$id <- as.character(D$id)
D$group2 <- factor(people2$class[sapply(D$id, function(x) which(people2$id==x))])

D
#>    id rate group2
#> 1 101 13.2      2
#> 2 102 15.3      2
#> 3 103 16.3      3
#> 4 104 19.1      1

#maybe easier
people2 <- data.frame(id = 101:104, class = c(2,2,3,1))
D <- data.frame(id = 101:104, rate = c(13.2, 15.3, 16.3, 19.1))
merge(D, people2, by = "id")
#>    id rate class
#> 1 101 13.2     2
#> 2 102 15.3     2
#> 3 103 16.3     3
#> 4 104 19.1     1

Created on 2019-07-19 by the reprex package (v0.2.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.