r - 如何隐藏列表中数据框的列类型?
问题描述
我在名为 df.list 的列表中有以下两个数据框
df1 <- data.frame(name=c("a","b","c"),total=c("1","2","3"),other=c("100","200","300"))
df2 <- data.frame(name=c("d","e","f"),total=c("4","5","6"),other=c("100","200","300"))
df.list <- list(df1,df2)
[[1]]
name total other
1 a 1 100
2 b 2 200
3 c 3 300
[[2]]
name total other
1 d 4 100
2 e 5 200
3 f 6 300
我希望能够遍历列表中的每个数据框并将total
andother
列转换为数字,并将其分配回 df.list
我尝试了以下方法,但似乎不起作用
lapply(df.list, function(x) as.numeric(x[2:3]))
解决方案
We may use type.convert
directly on the list
df.list2 <- type.convert(df.list, as.is = TRUE)
-checking the structure
str(df.list2)
List of 2
$ :'data.frame': 3 obs. of 3 variables:
..$ name : chr [1:3] "a" "b" "c"
..$ total: int [1:3] 1 2 3
..$ other: int [1:3] 100 200 300
$ :'data.frame': 3 obs. of 3 variables:
..$ name : chr [1:3] "d" "e" "f"
..$ total: int [1:3] 4 5 6
..$ other: int [1:3] 100 200 300
If we want to loop, then as.integer/as.numeric
works on vectors. So, we need to loop again
df.list2 <- lapply(df.list, function(x) {
x[2:3] <- lapply(x[2:3], as.integer)
x})
推荐阅读
- html - 在 Firefox 中显示顶部而不是底部的下拉菜单
- python - Python将“True”和“False”解析为字符串
- go - GO中字符串的ASCII编码
- c# - 操作来自 App.config 的 url 的正确方法
- javascript - 在 javascript 中,是否使用 eval() 将下拉列表中选择的文本与数组相匹配,或者我错过了更好的方法来做到这一点?
- javascript - 使用 Javascript 从数据中过滤选定的子项
- ios - Xcode 中的自动布局失败。不小心禁用了,如何恢复原状?
- php - 流明调度程序无法使用 cron 作业
- c - 在 c 的结构中初始化 int 类型的灵活数组时出错
- python - python中的矩阵匹配