Changing the values ​​of multiple column elements for a data frame in R

I am trying to update a bunch of columns by adding and subtracting SD for each column value. SD for this column.

Below is the reproducible code that I came up with, but I believe that this is not the most efficient way to do this. Can someone suggest me a better way to do this?

Essentially, there are 20 rows and 9 columns. I just need two separate data frames that have values ​​for each column, adjusted by adding the SD of this column, and the other by subtracting SD from each column value.

##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)
+4
source share
2 answers

sweep ( ?sweep R )

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)
+2

dataframe , 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]
}
+1

All Articles