gpt4 book ai didi

R标准化数据框中的数字变量,同时保留因子变量

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

我在 R 中加载了一个数据框 (dcc),我已经缩小范围以完成案例。

str(dcc)

'data.frame': 41715 obs. of 9 variables:
$ XCoord : num 661382 661412 661442 661472 661502 ...
$ YCoord : num 648092 648092 648092 648092 648092 ...
$ OBJECTID : int 1 2 3 4 5 6 7 8 9 10 ...
$ POINTID : int 1 2 3 4 5 6 7 8 9 10 ...
$ GRID_CODE : int 0 0 0 0 0 0 0 0 0 0 ...
$ APPL_COST_DIST_RIV_COAST: num 21350 21674 22185 22748 23448 ...
$ APPL_DEM30 : int 785 793 792 769 765 777 784 789 781 751 ...
$ APPL_DEM30_SLOPE : num 19.7 13.3 18.6 23.2 21 ...
$ APPL_SITE_NONSITE : Factor w/ 2 levels "0","1": 1 1 1 1 1 1 1 1 1 1 ...

我想通过减去平均值并除以标准偏差来标准化数字和整数变量。当我应用以下代码时,我无意中从数据框中删除了因子变量 APPL_SITE_NONSITE:
ind <- sapply(dcc, is.numeric)
dcc.s<-sapply(dcc[,ind], function(x) (x-mean(x))/sd(x))
dcc.s<-data.frame(dcc.s)

如果我没记错的话,发生这种情况是因为该变量的 ind=FALSE。似乎我需要 for 循环和 if/else 语句的某种组合来标准化数字变量并单独保留因子变量。我已经尝试了许多排列,但不断出现错误。例如,以下代码:
dcc.s <- for (i in 1:ncol(dcc)){ sapply(dcc[,i],
if (is.numeric(dcc[,i])==TRUE) {
function(x) (x-mean(x))/sd(x) }
else {dcc[,i]})
}

返回错误:

match.fun(FUN) 中的错误:
c("'if (is.numeric(dcc[, i]) == TRUE) {' 不是函数、字符或符号", "' function(x) (x - mean(x))/sd(x )' 不是函数、字符或符号", "'} else {' 不是函数、字符或符号", "' dcc[, i]' 不是函数、字符或符号", "'}'不是函数、字符或符号")

也许这是一个简单的格式错误或错位的括号,但我完全被卡住了。如果有更优雅的方法来做到这一点,我对其他方法持开放态度。任何帮助将非常感激。

最佳答案

您需要使用 rapply 而不是 sapply

set.seed(1)
> df=data.frame(A=rnorm(10),b=1:10,C=as.factor(rep(1:2,5)))
> str(df)
'data.frame': 10 obs. of 3 variables:
$ A: num -0.626 0.184 -0.836 1.595 0.33 ...
$ b: int 1 2 3 4 5 6 7 8 9 10
$ C: Factor w/ 2 levels "1","2": 1 2 1 2 1 2 1 2 1 2

您需要使用的代码:
> D=rapply(df,scale,c("numeric","integer"),how="replace")
> D
A b C
1 -0.97190653 -1.4863011 1
2 0.06589991 -1.1560120 2
3 -1.23987805 -0.8257228 1
4 1.87433300 -0.4954337 2
5 0.25276523 -0.1651446 1
6 -1.22045645 0.1651446 2
7 0.45507643 0.4954337 1
8 0.77649606 0.8257228 2
9 0.56826358 1.1560120 1
10 -0.56059319 1.4863011 2
> str(D)
'data.frame': 10 obs. of 3 variables:
$ A: num [1:10, 1] -0.9719 0.0659 -1.2399 1.8743 0.2528 ...
..- attr(*, "scaled:center")= num 0.132
..- attr(*, "scaled:scale")= num 0.781
$ b: num [1:10, 1] -1.486 -1.156 -0.826 -0.495 -0.165 ...
..- attr(*, "scaled:center")= num 5.5
..- attr(*, "scaled:scale")= num 3.03
$ C: Factor w/ 2 levels "1","2": 1 2 1 2 1 2 1 2 1 2
>

关于R标准化数据框中的数字变量,同时保留因子变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633147/

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