-1

(I am a SAS programmer trying to learn R).

I have multiple numeric columns. Using dplyr, I want to get a mean of those multiple values per each row. In SAS, this would be:

newvariable = mean(of x1, x2, x3, x4, x5);

I imagined it would look like this in R, but it just generates an error message.

Code:

time1data %>%
  mutate(newvariable = mean(of x1, x2, x3, x4, x5)) %>%
  head
smci
  • 32,567
  • 20
  • 113
  • 146
Kaz
  • 37
  • 6
  • what error message? can you also pleasae include a sample of your data? You can do that by typeing `dput(head(data))` and adding the output to your questions – morgan121 Jul 13 '19 at 02:58
  • also `of` is not a real thing in R – morgan121 Jul 13 '19 at 02:59
  • Try `time1data %>% mutate(newvariable = rowMeans(.[c("x1", "x2", "x3", "x4", "x5")]))` – Ronak Shah Jul 13 '19 at 02:59
  • 3
    A base R solution could be something like: `rowMeans(time1data[,c("x1", "x2", "x3", "x4", "x5")])` – Dave2e Jul 13 '19 at 03:01
  • Thanks, this worked: time1data$newvar<-rowMeans(time1data[,c("x1", "x2", "x3", "x4", "x5", "x", "x6", "x7")]) I added "na.rm=TRUE" to it, which has to do with how to treat missing values and it didn't generate an error message. Do you think this is necessary? time1data$newvar<-rowMeans(time1data[,c("x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8")],na.rm=TRUE) – Kaz Jul 13 '19 at 03:27
  • its almost always necessary. if false, `mean(c(1,2,3,NA)) = NA` super annoying – morgan121 Jul 13 '19 at 03:56

1 Answers1

2
library(dplyr)
library(tidyr)

# convert to a data frame if not already.
data_frame <- as.data.frame(your_data)

# These are the columns I used for testing for data with five columns
# and are to help you understand the next line of code.
colnames(dataframe) <- c("First", "Second", "Third", "Forth", "Fifth")

# tidyverse gather() via install.packages("tidyverse")
# index is the name of the "key" column, "Group_Mean" of value column
# Kept the convert = True otherwise, they become factor or strings
df.gather.col <- gather(data_frame, key="index", value="Group_Mean",
                        First, Second, Third, Forth, Fifth, 
                        convert=True)

#just prints it out.      
 df.gather.col 

Further reading R gather usage and most importantly, hopes this helps.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
tcratius
  • 525
  • 6
  • 15
  • I would suggest using the naming convention `_` for `.` to stay in line with `tidyverse` principles. – NelsonGon Jul 13 '19 at 04:56
  • Thank you all. This was the first time I asked a question here. I really appreciate all of your responses. I couldn't understand some replies and didn't know how to respond to. Sorry, but thank you! – Kaz Jul 14 '19 at 01:22