gpt4 book ai didi

r - 如何在 R 中更改多列的数据类型?

转载 作者:行者123 更新时间:2023-12-01 12:27:50 25 4
gpt4 key购买 nike

我想将所有以 _FL 结尾的字段从字符转换为数字。我认为这段代码可以工作,但事实并非如此:所有这些字段都填满了 NA。有什么问题吗?

library(data.table)
#s = fread('filename.csv',header = TRUE,sep = ";",dec = ".")
s=data.table(ID=(1:10), B=rnorm(10), C_FL=c("I","N"), D_FL=(0:1), E_FL=c("N","I"))
cn=colnames(s)
# Change all fields ending with _FL from "N"/"I" to numeric 0/1
for (i in cn){
if(substr(i,nchar(i)-2,nchar(i))=='_FL'){
s[,i] = as.numeric(gsub("I",1,gsub("N",0,s[,i])))
}
}

最佳答案

另一种选择是使用intersect() 找到包含“_FL”的字符 列,并根据条件= 将它们转换为二进制列= "N":

library(data.table)

# Find relevant columns
chr.cols <- names(s)[intersect(which(sapply(s,is.character)),
grep("_FL", names(s)))]
# Convert to numeric
for(col in chr.cols) set(s, j = col, value = as.numeric(s[[col]] == "N"))

# See result
> s
ID B C_FL D_FL E_FL
1: 1 0.6175364 0 0 1
2: 2 -0.9500318 1 1 0
3: 3 -0.6341547 0 0 1
4: 4 -0.8055696 1 1 0
5: 5 -0.3139938 0 0 1
6: 6 0.4676558 1 1 0
7: 7 1.6455591 0 0 1
8: 8 -0.4544377 1 1 0
9: 9 0.3512442 0 0 1
10: 10 0.3828367 1 1 0

关于r - 如何在 R 中更改多列的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37721607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com