【发布时间】:2018-04-02 14:05:31
【问题描述】:
我是一个具有不同列的数据框,其中包含来自不同评估者的字符串答案,他们在答案中使用了随机的大写或小写。我想将所有内容都转换为小写。我的代码如下:
# Creating a reproducible data frame similar to what I am working with
dfrm <- data.frame(a = sample(names(islands))[1:20],
b = sample(unname(islands))[1:20],
c = sample(names(islands))[1:20],
d = sample(unname(islands))[1:20],
e = sample(names(islands))[1:20],
f = sample(unname(islands))[1:20],
g = sample(names(islands))[1:20],
h = sample(unname(islands))[1:20])
# This is how I did it originally by writing everything explicitly:
dfrm1 <- dfrm
dfrm1$a <- tolower(dfrm1$a)
dfrm1$c <- tolower(dfrm1$c)
dfrm1$e <- tolower(dfrm1$e)
dfrm1$g <- tolower(dfrm1$g)
head(dfrm1) #Works as intended
问题是随着评估者数量的增加,我不断地复制粘贴错误。我试图通过为tolower 编写一个函数来简化我的代码,并使用sapply 循环它,但最终的数据帧看起来不像我想要的:
# function and sapply:
dfrm2 <- dfrm
my_list <- c("a", "c", "e", "g")
my_low <- function(x){dfrm2[,x] <- tolower(dfrm2[,x])}
sapply(my_list, my_low) #Didn't work
# Alternative approach:
dfrm2 <- as.data.frame(sapply(my_list, my_low))
head(dfrm2) #Lost the numbers
我错过了什么?
我知道这一定是一个非常基本的概念,我没有得到。有this question and answer that I simply couldn't follow 和this one where my non-working solution simply seems to work。任何帮助表示赞赏,谢谢!
【问题讨论】: