Reputation: 45
I am trying to figure out how to perform a basic math function on multiple columns using either mutate_all or mutate_at. I need to convert a number by a decimal (divide each column by 10). This is the second part after I use a summarise_at to obtain mean values for each column. cn<-c("tmin_1", "tmin_2", "tmin_3", "tmin_4", "tmin_5", "tmin_6", "tmin_7", "tmin_8", "tmin_9", "tmin_10", "tmin_11", "tmin_12")
a<-data.frame(replicate(12,sample(1:10,6,rep=TRUE)))
names(a)[1:12]<-cn
a$"S"<-c("A","A","A","B","B","B")
a2 <- a %>%
filter(S == "A") %>%
summarise_at(vars(tmin_1:tmin_12), funs(mean))
Works up to here. When I add "mutate_all(y=y/10)" at the end it doesn't work.
The above code returns a new object with 1 row and 12 columns, which is what I want. The columns contain mean values. Now I just need to divide each value by 10 to convert the number. I tried mutate_all() but it is not working for me. I'm not sure how to execute /10
to each column. I don't know how to refer to the columns.
ON a related note, can someone provide a simpler tidy way to generate the above example data frame? I would like to create a table of random numbers in several columns, assign characters to a single column, and name each column in a single set pipes.
Thanks!
Upvotes: 1
Views: 648
Reputation: 2301
Note that base R often allows you to easily apply scalar operations to vectors of data. For example, your df a
which has 12 numeric columns and a single character column at the end. Then you simply divide the numeric columns by 10. This base operation would provide the desired result:
a[ , 1:12] <- a[ , 1:12] / 10
If the character column was not present the scalar operation would simply be:
a <- a / 10
Upvotes: 0
Reputation: 887038
The 'S' column is character
, so may need mutate_if
library(dplyr)
a %>%
filter(S == "A") %>%
mutate_if(is.numeric, ~ ./10)
If it is on the 'a2'
a2 %>%
mutate_all(list(y = ~ ./10))
Upvotes: 1