number<-list(matrix(1:6,2,3),matrix(2:7,2,3))
fruit<-c("apple","banana","pear","orange","berry","grape","watermelon")
目标:选择列表中的前两列&#34;数字&#34;,然后将相关号码替换为&#34; fruit&#34;中的名称。
我的代码如下。
result<-lapply(number,function(a) {fruit[a[,c(1,2)]]})
但结果不是我想要的。
[[1]]
[1] "apple" "banana" "pear" "orange"
[[2]]
[1] "banana" "pear" "orange" "berry"
虽然我的预期结果如下;
[[1]]
[1] "apple" "pear"
[2] "banana" "orange"
[[2]]
[1] "banana" "orange"
[2] "pear" "berry"
你能帮我解决这个问题,谢谢!
答案 0 :(得分:2)
它为您提供了正确的答案,但它会对您的矩阵进行矢量化。尝试:
result <- lapply(number,function(a) {matrix(fruit[a[,c(1,2)]],nrow=nrow(a))})