Reputation: 409
I am trying to get a series of the sum of records grouped by two variables: column 'a' and then with the rest of the columns in my dataset.
When I run this below:
vars <- c(colnames(df))
vars<-vars[-1]
counting<-function(index) {
count(df,a,get(index))
}
vars[]<-lapply(vars,FUN=counting)
the name for the column generated by get(index) is named "get(index)" in my list vars. How can I change this so that the column name in the output is the same as the original column name?
For example, (this dataframe is modified from a tutorial in datacamp), if I have this dataframe:
First.Name <- c("John", "Edgar", "Walt", "Jane")
Second.Name <- c("Doe", "Poe", "Whitman", "Austen")
Sex <- c("MALE", "MALE", "MALE", "FEMALE")
writers_df <- data.frame(First.Name, Second.Name, Sex)
And I wanted to count how many rows have unique combinations of Sex and other variables, I would run:
vars <- c(colnames(writers_df))
vars<-vars[-3]
counting<-function(index) {
count(df,Sex,get(index))
}
vars[]<-lapply(vars,FUN=counting)
The output of one of the tables would then look like:
Sex get(index) n
M John 1
M Edgar 1
M Walt 1
F Jane 1
How can I get the column get(index) named First.Name without manually changing it "by hand"?
Upvotes: 0
Views: 86
Reputation: 16090
Use the underscore version: count_
:
counting <- function(index) {
count_(writers_df, c('Sex', index))
}
> lapply(vars,FUN=counting)
[[1]]
# A tibble: 4 x 3
Sex First.Name n
<fct> <fct> <int>
1 FEMALE Jane 1
2 MALE Edgar 1
3 MALE John 1
4 MALE Walt 1
[[2]]
# A tibble: 4 x 3
Sex Second.Name n
<fct> <fct> <int>
1 FEMALE Austen 1
2 MALE Doe 1
3 MALE Poe 1
4 MALE Whitman 1
[[3]]
# A tibble: 2 x 2
Sex n
<fct> <int>
1 FEMALE 1
2 MALE 3
Upvotes: 2
Reputation: 173577
Try this:
counting<-function(var) {
count(writers_df,Sex,!!rlang::sym(var))
}
> lapply(vars,counting)
[[1]]
# A tibble: 4 x 3
Sex First.Name n
<fctr> <fctr> <int>
1 FEMALE Jane 1
2 MALE Edgar 1
3 MALE John 1
4 MALE Walt 1
[[2]]
# A tibble: 4 x 3
Sex Second.Name n
<fctr> <fctr> <int>
1 FEMALE Austen 1
2 MALE Doe 1
3 MALE Poe 1
4 MALE Whitman 1
Upvotes: 1