gpt4 book ai didi

r - 将R中的所有列从系数更改为数值

转载 作者:行者123 更新时间:2023-12-02 05:26:49 26 4
gpt4 key购买 nike

我正在使用一个大数据集,这会造成一些麻烦,因为我将数据集的某些列视为因素。如何将所有列从factor转换为数值,而不必逐列进行?

我试图应用一个小循环,但它返回NA值。这是适用于此情况的样本数据:

data <- structure(list(v1 = c(22.394, 43.72, 58.544, 56.877, 1.659, 29.142, 
67.836, 68.851), v2 = c(144.373, 72.3, 119.418, 112.429, 35.779,
41.661, 166.941, 126.548), v3 = structure(c(33L, 29L, 33L, 5L,
13L, 31L, 5L, 8L), .Label = c("", "#VALUE!", "0", "1", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "2", "20",
"21", "22", "23", "24", "25", "26", "28", "29", "3", "30", "32",
"33", "4", "48", "5", "6", "7", "8", "9"), class = "factor"),
v4 = structure(c(24L, 6L, 22L, 23L, 16L, 22L, 23L, 26L), .Label = c("",
"-1", "-2", "-4", "#VALUE!", "0", "1", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "2", "24", "28",
"29", "3", "4", "5", "6", "7", "8", "9"), class = "factor")), .Names = c("v1",
"v2", "v3", "v4"), row.names = c("4", "5", "6", "7", "8", "9",
"10", "11"), class = "data.frame")

for (i in 1:ncol(data)){
data[,i] <- as.numeric(as.character(data[i]))
} ## returns NAs

我可以应用一些命令将所有这些列转换为数字类吗?

最佳答案

这行得通,但是我认为您的数据具有奇数字符或空格,这使它作为要素被读入。您可以尝试使用stringsAsFactors = FALSE参数阅读。但是仍然无法解决字符对数字读入的问题。这是一个解决方法:

data[] <- lapply(data, function(x) as.numeric(as.character(x)))

## > str(data)
## 'data.frame': 8 obs. of 4 variables:
## $ v1: num 22.39 43.72 58.54 56.88 1.66 ...
## $ v2: num 144.4 72.3 119.4 112.4 35.8 ...
## $ v3: num 7 4 7 10 18 5 10 13
## $ v4: num 5 0 3 4 18 3 4 7

关于r - 将R中的所有列从系数更改为数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23915131/

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