I have a dataframe which is called myData
.
library(dplyr)
myLines="
name1 name2 value
Simon Simon 42
Simon George 34
"
myData <- read.table(text=myLines, header=TRUE)
What code (preferably dplyr) do I have to apply to myData
in order to get the following result?
name value
Simon 118
George 34
The answer needs to be applicable to examples, where I have many name-columns instead of just two.
You can obtain all name-value pairs with gather
and then summarize:
library(tidyr)
myData %>%
gather(var, name, - value) %>%
group_by(name) %>%
summarise(value = sum(value))
# # A tibble: 2 x 2
# name value
# <chr> <int>
# 1 George 34
# 2 Simon 118
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.