Reputation: 21
df ex:
# A tibble: 20 x 2
Autoswing `Duration(seconds)`
<chr> <dbl>
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✗ Inf
15 ✗ 14
16 ✗ Inf
17 ✗ Inf
18 ✗ Inf
19 ✗ Inf
20 ✗ Inf
I would like to change all ✗ to ✓ in Autoswing if Duration(seconds) is inf. I was trying to use an if statement
Upvotes: 0
Views: 58
Reputation: 78927
Another base R option is to use transform
:
df <- transform(df, Autoswing = ifelse(`Duration(seconds)` == "Inf", "✓", Autoswing))
Output:
Autoswing Duration.seconds.
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✓ Inf
15 ✗ 14
16 ✓ Inf
17 ✓ Inf
18 ✓ Inf
19 ✓ Inf
20 ✓ Inf
Upvotes: 1
Reputation: 887118
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>
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✓ Inf
15 ✗ 14
16 ✓ Inf
17 ✓ Inf
18 ✓ Inf
19 ✓ Inf
20 ✓ Inf
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>
1 ✗ 4
2 ✗ 5
3 ✗ 7
4 ✗ 6
5 ✗ 8
6 ✗ 9
7 ✗ 11
8 ✗ 16
9 ✗ 16
10 ✗ 8
11 ✗ 12
12 ✗ 15
13 ✗ 10
14 ✓ Inf
15 ✗ 14
16 ✓ Inf
17 ✓ Inf
18 ✓ Inf
19 ✓ Inf
20 ✓ Inf
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))
Upvotes: 1
Reputation: 10627
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)
Upvotes: 0
Reputation: 8811
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
Upvotes: 0