-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
  • 29,564
  • 18
  • 109
  • 144
Kaz
  • 37
  • 5

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
  • 12,469
  • 5
  • 25
  • 52
tcratius
  • 515
  • 6
  • 13
  • 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