将每个列表对象中的特定列转换为特定格式的最佳方法是什么?
例如,我有一个包含四个对象的列表(每个对象都是一个数据框),我想将每个data.frame中的第3列从double更改为整数?
我猜测了一些事情,但我不知道使用什么特定的synthax。我在努力:
lapply(df,function(x){as.numeric(var1(x))})
但它不起作用。
谢谢!
答案 0 :(得分:4)
是的,lapply
在这里效果很好:
lapply(listofdfs, function(df) { # loop through each data.frame in list
df[ , 3] <- as.integer(df[ , 3]) # make the 3rd column of type integer
df # return the new data.frame
})
答案 1 :(得分:2)
这只是C. Braun答案的替代品。
您还可以使用map()
库中的purr
功能。
输入:
library(tidyverse)
df <- tibble(a = c(1, 2, 3), b =c(4, 5, 6), d = c(7, 8, 9))
myList <- list(df, df, df)
myList
方法:
map(myList, ~(.x %>% mutate_at(vars(3), funs(as.integer(.)))))
输出:
[[1]]
# A tibble: 3 x 3
a b d
<dbl> <dbl> <int>
1 1. 4. 7
2 2. 5. 8
3 3. 6. 9
[[2]]
# A tibble: 3 x 3
a b d
<dbl> <dbl> <int>
1 1. 4. 7
2 2. 5. 8
3 3. 6. 9
[[3]]
# A tibble: 3 x 3
a b d
<dbl> <dbl> <int>
1 1. 4. 7
2 2. 5. 8
3 3. 6. 9
答案 2 :(得分:0)
您可以使用:
dlist2 <- lapply(dlist,function(x){
y <- x
y[,coltochange] <- as.numeric(x[,coltochange])
return(y)
} )
简单示例:
data <- data.frame(cbind(c("1","2","3","4",NA),c(1:5)),stringsAsFactors = F)
typeof(data[,1]) #character
dlist <- list(data,data,data)
coltochange <- 1
dlist2 <- lapply(dlist,function(x){
y <- x
y[,coltochange] <- as.numeric(x[,coltochange])
return(y)
} )
typeof(dlist[[1]][,1]) #character
typeof(dlist2[[1]][,1]) #double