将列表转换为小写字母(R语言)

29

Var1 是一个列表:

var1 <- list(c("Parts of a Day", "Time in Astronomy", "Star"),  c("Tree Tall", "Pine Tree"))

如何将所有字符转换为小写?期望的答案是以下列表:

var1 <- list(c("parts of a day", "time in astronomy", "star"),  c("tree tall", "pine tree"))

我使用了

as.list(tolower(var1))

但是它会给出带有不需要的反斜杠的以下答案

[[1]]
[1] "c(\"parts of a day\", \"time in astronomy\", \"star\")"

[[2]]
[1] "c(\"tree tall\", \"pine tree\")"

谢谢。

2个回答

42
您应该使用lapply函数将列表中的每个字符向量转换为小写。
lapply(var1, tolower)

# [[1]]
# [1] "parts of a day"    "time in astronomy" "star"             
# 
# [[2]]
# [1] "tree tall" "pine tree"
否则,tolower会对整个列表进行as.character()操作,这不是您想要的。

7
为什么要使用sapply而不是lapply?这里不需要简化。 - thelatemail

1
请使用 gsub
gsub("/", "", var1)
as.list(tolower(var1))

这将从您的变量中删除所有的 /。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接