-1

I am trying to calculate the standard deviation for each participant across certain columns (or variables) and have this as a new variable in my dataframe. In Excel, it's relatively simple, you would just use =stdev and then select the columns you want and then populate it for the rest of the participants. It's also very simple in SPSS, you would just compute a new variable and then make it equal to var(item1,item2,item3). But in R, I can't get it to work. So essentially, this is what I want my r data-frame to end up looking like:

The end goal

Any help is greatly appreciated!

helpme
  • 1
  • 2
    Welcome to R and to StackOverflow. When you type `??"standard deviation"` R will show you a list of functions matching the search term, here "standard deviation" (in quotes as it contains a space). One of those is `sd` in the (base) package `stats`. Doing `?sd` will then show you its help, and `example(sd)` will run the example(s) from that help page. This should get you on the right way... – Dirk Eddelbuettel May 19 '21 at 23:33
  • 1
    Another request: can you please show us a [mcve]? You could do that by reading the data you showed us into R (with `read.csv()` or `readxl::read_excel()`) and then using `dput()` to put the data into a useful format (then paste the results into your answer as text in a code block). Something *approximately* like `apply(my_data[,3:5], 1, sd)` will do what you want – Ben Bolker May 19 '21 at 23:37
  • 1
    You said you "can't get it to work". Can you edit your question to include the code you've tried? – Ben Bolker May 19 '21 at 23:38

1 Answers1

0

If you want to calculate the std dev of rows of participants you could use the apply function on your dataframe. If you want to use only certain columns to calculate the std dev, you can specify those in the apply dataframe parameter. You can also directly append the std dev calculation vector to your dataframe. All in one line of code. Here's how it works using the sample dataframe mtcars. Let's limit the columns used to col# 1, 3, 6. Then:

mtcars$sd <- apply(mtcars[, c(1, 3, 6)], 1, sd)
head(mtcars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb        sd
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4  86.04968
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  85.96296
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  56.04571
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 142.14174
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 201.59927
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 123.89640

You can see the std devs were calculated and a new column sd was attached to the dataframe.

SteveM
  • 2,226
  • 3
  • 12
  • 16