更改 R 中数据框的多个列元素的值

Changing values of multiple column elements for dataframe in R

我正在尝试通过对列的每个值添加和减去 SD 来更新一组列。 SD 是给定列的。

下面是我想出的可重现代码,但我觉得这不是最有效的方法。有人可以建议我更好的方法吗?

本质上,有 20 行和 9 columns.I 只需要两个单独的数据帧,一个数据帧通过添加该列的 SD 来调整每一列的值,另一个通过从列的每个值中减去 SD 来调整。

##Example
##data frame containing 9 columns and 20 rows
Hi<-data.frame(replicate(9,sample(0:20,20,rep=TRUE)))  
##Standard Deviation calcualted for each row and stored in an object - i don't what this objcet is -vector, list, dataframe ?
Hi_SD<-apply(Hi,2,sd)
#data frame converted to matrix to allow addition of SD to each value
Hi_Matrix<-as.matrix(Hi,rownames.force=FALSE)
#a new object created that will store values(original+1SD) for each variable 
Hi_SDValues<-NULL
#variable re-created -contains sum of first column of matrix and first element of list. I have only done this for 2 columns for the purposes of this example. however, all columns would need to be recreated
Hi_SDValues$X1<-Hi_Matrix[,1]+Hi_SD[1]
Hi_SDValues$X2<-Hi_Matrix[,2]+Hi_SD[2]
#convert the object back to a dataframe
Hi_SDValues<-as.data.frame(Hi_SDValues)

##Repeat for one SD less
Hi_SDValues_Less<-NULL
Hi_SDValues_Less$X1<-Hi_Matrix[,1]-Hi_SD[1]
Hi_SDValues_Less$X2<-Hi_Matrix[,2]-Hi_SD[2]
Hi_SDValues_Less<-as.data.frame(Hi_SDValues_Less)

您无需将数据帧转换为矩阵即可添加 SD

Hi<-data.frame(replicate(9,sample(0:20,20,rep=TRUE)))  
Hi_SD<-apply(Hi,2,sd) # Hi_SD is a named numeric vector

Hi_SDValues<-Hi # Creating a new dataframe that we will add the SDs to

# Loop through all columns (there are many ways to do this)
for (i in 1:9){
    Hi_SDValues[,i]<-Hi_SDValues[,i]+Hi_SD[i]
}
# Do pretty much the same thing for the next dataframe
Hi_SDValues_Less <- Hi
for (i in 1:9){
    Hi_SDValues[,i]<-Hi_SDValues[,i]-Hi_SD[i]
}

这是 sweep 的工作(在 R 中为文档输入 ?sweep

Hi <- data.frame(replicate(9,sample(0:20,20,rep=TRUE)))  
Hi_SD <- apply(Hi,2,sd)
Hi_SD_subtracted <- sweep(Hi, 2, Hi_SD)