R - Unite without NA values [duplicate] - r

This question already has answers here:
Combine two or more columns in a dataframe into a new column with a new name
(9 answers)
Closed 3 years ago.
I have got multiple columns. All columns do have NA values in some rows. Is it possible to unite these columns without having the NA values in the new column?
Without NA values:
library(dplyr)
unite(mtcars, 'mpg_am', c('mpg','am'))
Creating fake data:
mtcars$NA_1 = ifelse(mtcars$mpg>20, NA, mtcars$mpg)
mtcars$NA_2 = ifelse(mtcars$cyl>6, NA, mtcars$mpg)
unite(mtcars, 'Var1', c('NA_1','NA_2'))
This will create values like
Var1
NA_21
15.5_NA
NA_NA
15.5_21
...
desired output:
Var1
21
15.5
NA
15.5_21
...

We can use unite with na.rm
library(tidyverse)
mtcars %>%
rownames_to_column('rn') %>%
mutate_at(vars(starts_with("NA")), as.character) %>%
unite(Var1, NA_1, NA_2, na.rm = TRUE) %>%
mutate(Var1 = na_if(Var1, "")) %>%
column_to_rownames('rn')
Or another option is coalesce instead of unite
mtcars %>%
mutate(Var1 = str_c(coalesce(NA_1, NA_2), coalesce(NA_2, NA_1), sep="_"))
Or another option is
mtcars %>%
mutate_at(vars(starts_with("NA")), list(~ replace_na(., ''))) %>%
mutate(Var1 = str_remove(na_if(str_c(NA_1, NA_2, sep="_"), '_'), '^_|_$') ) %>%
select(-NA_1, NA_2)

unite has got na.rm parameter which will remove NA values but for that column needs to be of character type.
library(dplyr)
library(tidyr)
mtcars %>%
mutate_at(vars(NA_1, NA_2), as.character) %>%
unite(Var1, NA_1, NA_2, na.rm = TRUE)
# mpg cyl disp hp drat wt qsec vs am gear carb Var1
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 21
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 21
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 22.8
#4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 21.4
#5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
#6 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 18.1_18.1
#.....
However, if both the values are NA then this will return empty values instead of NA, if we need NA strictly we can check for empty values and replace
mtcars %>%
mutate_at(vars(NA_1, NA_2), as.character) %>%
unite(Var1, NA_1, NA_2, na.rm = TRUE)
mutate(Var1 = replace(Var1, Var1 == "", NA_character_))
Without any packages we can use paste0 in base R
cols <- c('NA_1','NA_2')
mtcars["V1"] <- apply(mtcars[cols],1,function(x) paste0(na.omit(x), collapse = "-"))

Related

Recoding turns everything into the same value in R

I'm practicing R and I created a new column that had continuous numbers in them called ROI, and wanted to recode the number values into string values in R like this:
df = mutate(diabetes_df, ROI = ifelse(ROI < 18.5, 'Under', ROI))
df = mutate(diabetes_df, ROI = ifelse(ROI >= 18.5 & ROI <= 25, 'average', ROI))
diabetes_df = mutate(diabetes_df, ROI = ifelse(ROI > 25 & BMI <= 30, 'above average', ROI))
This works normally and it displays these words wherever the condition is met, however when i put the last ifelse statement :
df = mutate(diabetes_df, ROI = ifelse(ROI > 30, 'OVER', ROI))
It turns every value in the new column I made into the OVER value. I was wondering if anyone knew how to make it so that it would only say OVER for where the condition is met?
If ROI is a numeric column, the issue is that you are overwriting a numeric column with text values.
If ROI is not a numeric column, then inequality comparison on text strings works different from how you have assumed.
Note that all you commands take the form: df = mutate(df, ROI = ifelse(ROI <condition>, 'label', ROI). This means you are overwriting the original ROI values, and the replaced values will we used for subsequent comparisons.
Suppose df had only row with ROI = 10 then:
# df:
# ROI = 10
df2 = mutate(df, ROI = ifelse(ROI < 18.5, 'Under', ROI))
# compares 10 < 18.5
# replaces 10 with 'Under'
# df2:
# ROI = 'Under'
df3 = mutate(df2, ROI = ifelse(ROI > 30, 'OVER', ROI))
# compares 'Under' > 30
# After standardizing formats, compares 'Under' > '30' (conversion to string)
# replaces 'Under' with 'OVER'
Two possible solutions:
write to a different column, this is good practice
df %>%
mutate(ROI_label = NA) %>%
mutate(ROI_label = ifelse(ROI < 18.5, 'Under', ROI_label)) %>%
mutate(ROI_label = ifelse(ROI >= 18.5 & ROI <= 25, 'average', ROI_label)) %>%
mutate(ROI_label = ifelse(ROI > 25 & BMI <= 30, 'above average', ROI_label)) %>%
mutate(ROI_label = ifelse(ROI > 30, 'OVER', ROI_label))
use case_when, this is also good practice
df %>%
mutate(ROI = case_when(ROI < 18.5 ~ 'Under',
ROI >= 18.5 & ROI <= 25 ~ 'average',
ROI > 25 & BMI <= 30 ~ 'above average',
ROI > 30 ~ 'OVER'))
Even better, write to a different column and use case_when.
We can replicate the problem with the mtcars data frame. The following code on the third mutate() statement results in all rows getting the wt value set to High because after the first mutate(), the wt column is a vector of character values.
library(dplyr)
data(mtcars)
mtcars <- mutate(mtcars,wt = ifelse(wt < 2.6,"Low", wt))
# at this point, wt is character
str(mtcars$wt)
> str(mtcars$wt)
chr [1:32] "2.62" "2.875" "Low" "3.215" "3.44" "3.46" "3.57" "3.19" "3.15" ...
By the third mutate() all rows meet the condition of TRUE for the if_else() based on a character string comparison where the string values of Low and Medium are greater than the number 3.61.
mtcars <- mutate(mtcars, wt = ifelse( 2.6 <= wt & wt <= 3.61,"Medium",wt))
mtcars <- mutate(mtcars, wt = ifelse( wt > 3.61,"High",wt))
...and the output:
> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 High 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 High 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 High 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 High 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 High 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 High 20.22 1 0 3 1
We can prevent this behavior by using case_when(), which makes all of the comparisons to the numeric version of wt in a single pass of the data.
# use case_when()
data(mtcars)
mtcars %>% mutate(wt = case_when(
wt < 2.6 ~ "Low",
wt >= 2.6 & wt <= 3.61 ~ "Medium",
wt > 3.61 ~ "High"
)) %>% head(.)
...and the output:
head(.)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 Medium 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 Medium 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 Low 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 Medium 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 Medium 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 Medium 20.22 1 0 3 1
>
From the comments to this answer, it wasn't clear to the OP how to save the changed column to the existing data frame. The following code snippet addresses that question.
data(mtcars)
mtcars %>% mutate(wt = case_when(
wt < 2.6 ~ "Low",
wt >= 2.6 & wt <= 3.61 ~ "Medium",
wt > 3.61 ~ "High"
)) -> mtcars

How can I get the length of an arbitrary data frame when piped in using Tidyr? [duplicate]

This question already has answers here:
Create an ID (row number) column
(10 answers)
Closed 3 years ago.
I have code like this:
bulk <- read_csv("data/food_bulk_raw.csv") %>%
mutate(Treatment = "bulk", Individual = seq_len(Timestamp))
seq_len() is creating a list of 1:length(Timestamp). It works because 'Timestamp' is a column of the data-frame. But let's say I didn't know anything about my data-frame: Perhaps I am creating a function. How could I indicate the length of the data-frame without first saving it as an object like I have below?
data002 <- read_csv("data/data002.csv")
data002 <- mutate(data002, New_Column = 1:nrow(data002))
You could use any of the following
library(tidyverse)
#Option 1
read_csv("data/food_bulk_raw.csv") %>%
mutate(Treatment = "bulk", Individual = seq_len(nrow(.)))
#Option 2
read_csv("data/food_bulk_raw.csv") %>%
mutate(Treatment = "bulk", Individual = seq(nrow(.)))
#Option 3
read_csv("data/food_bulk_raw.csv") %>%
mutate(Treatment = "bulk", Individual = sequence(nrow(.)))
All of these do not depend on any column but uses nrow to create sequence.
Also as #Marius commented, you could also use n() which returns number of rows instead of nrow. So in all of the above options nrow(.) can be replaced with n().
Apart from that we can also use row_number
read_csv("data/food_bulk_raw.csv") %>%
mutate(Treatment = "bulk", Individual = row_number())
To demonstrate, making a function
df_sequence_func <- function(df) {
df %>% mutate(Individual = seq_len(nrow(.)))
}
df_sequence_func(mtcars)
# mpg cyl disp hp drat wt qsec vs am gear carb Individual
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 1
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 2
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 3
#4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 4
#....
df_sequence_func(cars)
# speed dist Individual
#1 4 2 1
#2 4 10 2
#3 7 4 3
#4 7 22 4
#5 8 16 5
#6 9 10 6
#....
It returns a sequential row number irrespective of the columns or rows in the dataframe.
We can use data.table methods
library(data.table)
setDT(df)[, seq_len(.N)]
and it can be read with fread
fread("data/food_bulk_raw.csv")[,
c("Treatment", "Individual") := .("bulk", seq_len(.N))][]
Or in tidyverse
library(tidyverse)
rownames_to_column(data002, 'rn')
Or using
data002 %>%
mutate(New_Column = seq_len(n()))
Or in base R
df$newcolumn <- seq(nrow(df))

Use a character vector in the `by` argument

Within the data.table package in R, is there a way in order to use a character vector to be assigned within the by argument of the calculation?
Here is an example of what would be the desired output from this using mtcars:
mtcars <- data.table(mtcars)
ColSelect <- 'cyl' # One Column Option
mtcars[,.( AveMpg = mean(mpg)), by = .(ColSelect)] # Doesn't work
# Desired Output
cyl AveMpg
1: 6 19.74286
2: 4 26.66364
3: 8 15.10000
I know that this is possible to use assigning column names in j by enclosing the vector around brackets.
ColSelect <- 'AveMpg' # Column to be assigned for average mpg value
mtcars[,(ColSelect):= mean(mpg), by = .(cyl)]
head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb AveMpg
1: 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 19.74286
2: 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 19.74286
3: 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 26.66364
4: 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 19.74286
5: 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 15.10000
6: 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 19.74286
Is there a suggestion as to what to put in the by argument in order to achieve this?
From ?data.table in the by section it says that by accepts:
a single character string containing comma separated column names (where spaces are significant since column names may contain spaces
even at the start or end): e.g., DT[, sum(a), by="x,y,z"]
a character vector of column names: e.g., DT[, sum(a), by=c("x", "y")]
So yes, you can use the answer in #cccmir's response. You can also use c() as #akrun mentioned, but that seems slightly extraneous unless you want multiple columns.
The reason you cannot use .() syntax is that in data.table .() is an alias for list(). And according to the same help for by the list() syntax requires an expression of column names - not a character string.
Going off the examples in the by help if you wanted to use multiple variables and pass the names as characters you could do:
mtcars[,.( AveMpg = mean(mpg)), by = "cyl,am"]
mtcars[,.( AveMpg = mean(mpg)), by = c("cyl","am")]
try to use it like this
mtcars <- data.table(mtcars)
ColSelect <- 'cyl' # One Column Option
mtcars[, AveMpg := mean(mpg), by = ColSelect] # Should work

Naming a new variable based on a quosure

I'm trying to write a custom function that will compute a new variable based on values from a predefined vector of variables (e.g., vector_heavy) and then name the new variable based on an argument provided to the function (e.g., custom_name).
This variable naming is where my quosure skills are failing me. Any help is greatly appreciated.
library(tidyverse)
vector_heavy <- quos(disp, wt, cyl)
cv_compute <- function(data, cv_name, cv_vector){
cv_name <- enquo(cv_name)
data %>%
rowwise() %>%
mutate(!!cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>%
ungroup()
}
d <- cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)
My error message reads:
Error: unexpected '=' in:
" rowwise() %>%
mutate(!!cv_name ="
Removing the !! before cv_name within mutate() will result in a function that calculates a new variable literally named cv_name, and ignoring the custom_name I've included as an argument.
cv_compute <- function(data, cv_name, cv_vector){
cv_name <- enquo(cv_name)
data %>%
rowwise() %>%
mutate(cv_name = mean(c(!!!cv_vector), na.rm = TRUE)) %>%
ungroup()
}
How can I get this function to utilize the custom_name I supply as an argument for cv_name?
You need to use the := helper within mutate. You'll also need quo_name to convert the input to a string.
The mutate line of your function will then look like
mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE))
In its entirety:
cv_compute <- function(data, cv_name, cv_vector){
cv_name <- enquo(cv_name)
data %>%
rowwise() %>%
mutate(!!quo_name(cv_name) := mean(c(!!!cv_vector), na.rm = TRUE)) %>%
ungroup()
}
cv_compute(mtcars, cv_name = custom_name, cv_vector = vector_heavy)
mpg cyl disp hp drat wt qsec vs am gear carb custom_name
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 56.20667
2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 56.29167
3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 38.10667
4 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 89.07167
5 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 123.81333
6 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 78.15333

Avoiding and renaming .x and .y columns when merging or joining in r

Often I go about joining two dataframes together that have the same name. Is there a way to do this within the join-step so that I don't end up with a .x and a .y column? So the names might be 'original_mpg', and 'new_mpg'?
library(dplyr)
left_join(mtcars, mtcars[,c("mpg",'cyl')], by=c("cyl"))
names(mtcars) #ugh
Currently, this is an open issue with dplyr. You'll either have to rename before or after the join or use merge from base R, which takes a suffixes argument.
The default suffixes, c(".x", ".y"), can be overridden by passing them as a character vector of length 2:
library(dplyr)
left_join(mtcars, mtcars[,c("mpg","cyl")],
by = c("cyl"),
suffix = c("_original", "_new")) %>%
head()
Output
mpg_original cyl disp hp drat wt qsec vs am gear carb mpg_new
1 21 6 160 110 3.9 2.62 16.46 0 1 4 4 21.0
2 21 6 160 110 3.9 2.62 16.46 0 1 4 4 21.0
3 21 6 160 110 3.9 2.62 16.46 0 1 4 4 21.4
4 21 6 160 110 3.9 2.62 16.46 0 1 4 4 18.1
5 21 6 160 110 3.9 2.62 16.46 0 1 4 4 19.2
6 21 6 160 110 3.9 2.62 16.46 0 1 4 4 17.8
You can use suffix with a slightly modified function I found in the help of strsplit to make it a prefix
library(dplyr)
mt_cars <- left_join(mtcars, mtcars[,c("mpg","cyl")],
by = c("cyl"),
suffix = c("_original", "_new"))
strReverse <- function(x){
sapply(lapply(strsplit(x, "_"), rev), paste, collapse = "_")
}
colnames(mt_cars) <- strReverse(colnames(mt_cars))
Well, I had a similar question when I found this post.
I found a different solution to the question that I hope helps.
The solution is actually fairly simple, you generate a list with all the data frames you want to merge and use the reduce function.
library(dplyr)
df_list <- list(df1, df2, df3)
df <- Reduce(function(x, y) merge(x, y, all=TRUE), df_list)
This was a solution to another problem I had, I wanted to simplify merging multiple dataframes. But if you use two dataframes in the list, it works all the same and merging does not rename the columns.

Resources