Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R- squaring only specific columns

Tags:

r

Given a data set with a time stamp and several columns of data following it

data=
           hour          V1           V2          V3
1 2012-01-19 08:00:00  0.04551064  0.002851064  0.01842553
2 2012-01-19 09:00:00 -0.05305000 -0.052266667 -0.07455000
3 2012-01-19 10:00:00 -0.07518333 -0.101333333 -0.10670000
4 2012-01-19 11:00:00 -0.09195000 -0.099383333 -0.11176667
5 2012-01-19 12:00:00 -0.07743333 -0.074000000 -0.09106667
6 2012-01-19 13:00:00 -0.10978333 -0.096200000 -0.11343333

I would like to square the columns V1-V3 giving me this

data_sq=
         hour                V1           V2           V3
1    2012-01-19 08:00:00  0.002071218 8.128565e-06 0.0003395002
2    2012-01-19 09:00:00  0.002814303 2.731804e-03 0.0055577025
3    2012-01-19 10:00:00  0.005652534 1.026844e-02 0.0113848900
4    2012-01-19 11:00:00  0.008454803 9.877047e-03 0.0124917878
5    2012-01-19 12:00:00  0.005995921 5.476000e-03 0.0082931378
6    2012-01-19 13:00:00  0.012052380 9.254440e-03 0.0128671211

As for right now I just use

data_sq<-data^2

to get the square root. But it destroys the time stamp so I have to put it back in with something really awkward like

data_sqd<-cbind(data_sq,data$hour)

I tried

data_sq<-(data[,c(2:4)]^2

but I loose the time stamp as well

So how do I keep my time stamp column intact and specify which columns I want to square? My apologies for the lack of reproducible data, but I am hoping this is a simple enough question I can get away with it :)

like image 688
Vinterwoo Avatar asked Jun 07 '12 21:06

Vinterwoo


People also ask

How do I square multiple columns in R?

To add columns with square of each column in R data frame, we can use setNames function and cbind function for squaring each value. This might be required when we want to use squared form of variables in the data analysis.

How do I refer to a specific column in R?

To select a column in R you can use brackets e.g., YourDataFrame['Column'] will take the column named “Column”. Furthermore, we can also use dplyr and the select() function to get columns by name or index. For instance, select(YourDataFrame, c('A', 'B') will take the columns named “A” and “B” from the dataframe.


2 Answers

A one step solution:

data_sq <- transform(data, V1=V1^2, V2=V2^2, V3=V3^2)
like image 116
IRTFM Avatar answered Sep 21 '22 22:09

IRTFM


data_sq <- data # try not to use data, it's a function in base
data_sq[,2:4] <- data[,2:4]^2 # subsetting was off but you were close!
like image 43
Brandon Bertelsen Avatar answered Sep 19 '22 22:09

Brandon Bertelsen