我在数据框中有一个存储列表的列。下面是一个示例:
col
1 9, 8, 3, 7
2 8, 8, 8, 5
3 1, 8, 10, 4
4 3, 6, 1, 6
5 9, 9, 10, 4
6 8, 8, 9, 2
7 6, 10, 4, 7
8 6, 1, 5, 9
9 4, 7, 5, 10
10 7, 9, 2, 5
这是我用来生成上述示例的代码:
example <- data.frame(matrix(NA_real_, nrow=10, ncol=1))
colnames(example) <- "col"
x <- list(c(1,2,3,4))
for(y in 1:10) {
example$col[y] <- list(c(c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1))))
}
我想从数据列表中此列的所有这些列表中删除所有出现的数字9,以得到如下内容:
col
1 8, 3, 7
2 8, 8, 8, 5
3 1, 8, 10, 4
4 3, 6, 1, 6
5 10, 4
6 8, 8, 2
7 6, 10, 4, 7
8 6, 1, 5
9 4, 7, 5, 10
10 7, 2, 5
我目前正在尝试执行以下操作来解决此问题:
lapply(example, `[<-`, , "col", function(x) ifelse(x==1, NULL, 1))
我一直收到以下错误:
Error in lapply(example, `[<-`, , "col", function(x) ifelse(x == 1, NULL, :
incorrect number of subscripts on matrix
如何解决此错误并解决问题?还有其他解决方法吗?
答案 0 :(得分:6)
set.seed(123) # make sure to set.seed with random draws
example <- data.frame(matrix(NA_real_, nrow=10, ncol=1))
colnames(example) <- "col"
x <- list(c(1,2,3,4))
for(y in 1:10) {
example$col[y] <- list(c(c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1)),c(sample(1:10,1))))
}
example
col
1 3, 8, 5, 9
2 10, 1, 6, 9
3 6, 5, 10, 5
4 7, 6, 2, 9
5 3, 1, 4, 10
6 9, 7, 7, 10
7 7, 8, 6, 6
8 3, 2, 10, 10
9 7, 8, 1, 5
10 8, 3, 4, 3
library(purrr)
example$col <- map(example$col, ~.x[.x != 9])
example
col
1 3, 8, 5
2 10, 1, 6
3 6, 5, 10, 5
4 7, 6, 2
5 3, 1, 4, 10
6 7, 7, 10
7 7, 8, 6, 6
8 3, 2, 10, 10
9 7, 8, 1, 5
10 8, 3, 4, 3
答案 1 :(得分:5)
这是我使用purrr
包解决的方法。
map
函数类似于lapply
(如果尚未安装,则可能需要安装tidyverse
软件包):
library(tidyverse)
example %>%
mutate(col = map(col, ~gsub("9", NA_real_, .x)))
结果:
col
1 6, 10, 8, 8
2 3, 7, 1, 1
3 1, 2, 2, 4
4 2, 4, 6, 1
5 10, 8, 2, 8
6 NA, NA, 2, 4
7 5, 7, 8, NA
8 NA, 7, 6, 10
9 2, 6, 4, NA
10 4, 2, 10, 10
答案 2 :(得分:4)
基本R:
> example
col
1 10, 9, 3, 9
2 4, 7, 9, 3
3 5, 9, 5, 3
4 5, 4, 5, 4
5 10, 6, 2, 6
6 4, 7, 5, 9
7 1, 7, 1, 6
8 4, 9, 2, 10
9 3, 9, 3, 2
10 1, 6, 1, 4
example$col <- lapply(example$col, function(x){
x[x != 9]
})
> example
col
1 10, 3
2 4, 7, 3
3 5, 5, 3
4 5, 4, 5, 4
5 10, 6, 2, 6
6 4, 7, 5
7 1, 7, 1, 6
8 4, 2, 10
9 3, 3, 2
10 1, 6, 1, 4