lapply'ing 一个 for 循环 returns NULL
lapply'ing a for loop returns NULL
我有一个简单的列表
list1<-data.frame(col1=c("text;aaa","text", "text;aaa","text"), col2=1:4)
list2<- data.frame(col1=c("text;aaa","text", "text;aaa","text", "text", "text"), col2=1:6)
mylist<-list(list1,list2)
我现在想用 for 循环在 ; 之后子化所有文本,像这样
list.2 <- lapply(mylist, function(x){
for(i in 1:nrow(x)){
if(grepl(";",x[i,1]) == T){
x[i,1] <- gsub(";.*", "", x[i,1])
} else x[i,1] <- x[i,1]
}
} )
但是输出是NULL
list.2
[[1]]
NULL
[[2]]
NULL
我在这里错过了什么?
您需要 return x
在 lapply
内的函数中,否则什么也得不到 returned:
lapply(mylist, function(x){
for(i in 1:nrow(x)){
if(grepl(";",x[i,1])){
x[i,1] <- gsub(";.*", "", x[i,1])
} else x[i,1] <- x[i,1]
}
#return the x you modified previously
x
})
输出:
[[1]]
col1 col2
1 text 1
2 text 2
3 text 3
4 text 4
[[2]]
col1 col2
1 text 1
2 text 2
3 text 3
4 text 4
5 text 5
6 text 6
此外,作为旁注,您不需要 grepl(";",x[i,1]) == T
,而只需要 grepl(";",x[i,1])
,因为 grepl
returns TRUE
或 FALSE
无论如何(所以你不需要测试 TRUE==TRUE
)。
我有一个简单的列表
list1<-data.frame(col1=c("text;aaa","text", "text;aaa","text"), col2=1:4)
list2<- data.frame(col1=c("text;aaa","text", "text;aaa","text", "text", "text"), col2=1:6)
mylist<-list(list1,list2)
我现在想用 for 循环在 ; 之后子化所有文本,像这样
list.2 <- lapply(mylist, function(x){
for(i in 1:nrow(x)){
if(grepl(";",x[i,1]) == T){
x[i,1] <- gsub(";.*", "", x[i,1])
} else x[i,1] <- x[i,1]
}
} )
但是输出是NULL
list.2
[[1]]
NULL
[[2]]
NULL
我在这里错过了什么?
您需要 return x
在 lapply
内的函数中,否则什么也得不到 returned:
lapply(mylist, function(x){
for(i in 1:nrow(x)){
if(grepl(";",x[i,1])){
x[i,1] <- gsub(";.*", "", x[i,1])
} else x[i,1] <- x[i,1]
}
#return the x you modified previously
x
})
输出:
[[1]]
col1 col2
1 text 1
2 text 2
3 text 3
4 text 4
[[2]]
col1 col2
1 text 1
2 text 2
3 text 3
4 text 4
5 text 5
6 text 6
此外,作为旁注,您不需要 grepl(";",x[i,1]) == T
,而只需要 grepl(";",x[i,1])
,因为 grepl
returns TRUE
或 FALSE
无论如何(所以你不需要测试 TRUE==TRUE
)。