Home > Enterprise >  Change value in columns based off of another column in dataframe R
Change value in columns based off of another column in dataframe R

Time:10-04

    df ex:
# A tibble: 20 x 2
   Autoswing `Duration(seconds)`
   <chr>                   <dbl>
 14
 25
 37
 46
 58
 69
 711
 816
 916
108
1112
1215
1310
14Inf
1514
16Inf
17Inf
18Inf
19Inf
20Inf

I would like to change all ✗ to ✓ in Autoswing if Duration(seconds) is inf. I was trying to use an if statement

CodePudding user response:

We may use base R methods i.e check for infinite values with is.infinite to create a logical vector and do the assignment

df$Autoswing[is.infinite(df$`Duration(seconds)`)] <- "✓"

-output

> df
# A tibble: 20 × 2
   Autoswing `Duration(seconds)`
   <chr>                   <dbl>
 14
 25
 37
 46
 58
 69
 711
 816
 916
108
1112
1215
1310
14Inf
1514
16Inf
17Inf
18Inf
19Inf
20Inf

Or with data.table

library(data.table)
setDT(df)[is.infinite(`Duration(seconds)`), Autoswing := "✓"]

Or with dplyr using replace

library(dplyr)
df %>% 
   mutate(Autoswing = replace(Autoswing, is.infinite(`Duration(seconds)`), "✓"))
# A tibble: 20 × 2
   Autoswing `Duration(seconds)`
   <chr>                   <dbl>
 14
 25
 37
 46
 58
 69
 711
 816
 916
108
1112
1215
1310
14Inf
1514
16Inf
17Inf
18Inf
19Inf
20Inf

data

df <- structure(list(Autoswing = c("✗", "✗", "✗", "✗", "✗", 
"✗", "✗", "✗", "✗", "✗", "✗", "✗", "✗", "✗", 
"✗", "✗", "✗", "✗", "✗", "✗"), `Duration(seconds)` = c(4, 
5, 7, 6, 8, 9, 11, 16, 16, 8, 12, 15, 10, Inf, 14, Inf, Inf, 
Inf, Inf, Inf)), class = c("tbl_df", "tbl", "data.frame"), 
row.names = c(NA, 
-20L))

CodePudding user response:

Another base R option is to use transform:

df <- transform(df, Autoswing = ifelse(`Duration(seconds)` == "Inf", "✓", Autoswing))

Output:

   Autoswing Duration.seconds.
14
25
37
46
58
69
711
816
916
108
1112
1215
1310
14Inf
1514
16Inf
17Inf
18Inf
19Inf
20Inf

CodePudding user response:

library(dplyr)

df <-
  tibble(
    Autoswing = c("✗","✗"),
    `Duration(seconds)` = c(2,Inf)
  )

df %>% 
  mutate(Autoswing = if_else(`Duration(seconds)` == Inf,"✓",Autoswing)) %>% 
  glimpse()

Rows: 2
Columns: 2
$ Autoswing           <chr> "✗", "✓"
$ `Duration(seconds)` <dbl> 2, Inf

CodePudding user response:

library(tidyverse)

df <- tibble(
  Autoswing = c("✗", "✗"),
  Duration = c(5, Inf)
)
df
#> # A tibble: 2 × 2
#>   Autoswing Duration
#>   <chr>        <dbl>
#> 1 ✗                5
#> 2 ✗              Inf
df %>%
  mutate(
    Autoswing = Autoswing %>% map2_chr(Duration, ~ ifelse(is.infinite(.y), "✓", .x))
  )
#> # A tibble: 2 × 2
#>   Autoswing Duration
#>   <chr>        <dbl>
#> 1 ✗                5
#> 2 ✓              Inf

Created on 2021-10-03 by the reprex package (v2.0.1)

  • Related