I have a large dataframe
with a structure like this:
id v1 v2 v3 v4 v5
1 1 1 98 1 1
2 1 1 1 1 1
3 4 1 0 22 1
4 5 1 1 1 1
5 1 1 90 1 1
I would like to move from v2
all the way to v5
and if the variable value is greater than 1 character in length then it gets recoded to 9, so the resulting df
would be:
id v1 v2 v3 v4 v5
1 1 1 9 1 1
2 1 1 1 1 1
3 4 1 0 9 1
4 5 1 1 1 1
5 1 1 9 1 1
If this is a large dataframe
, using the data.table
library, you could do:
Reprex
library(data.table)
cols <- paste0("v", 2:5)
setDT(df)[, (cols) := lapply(.SD, function(x) fifelse(nchar(x) > 1, 9, x)), .SDcols = cols][]
#> id v1 v2 v3 v4 v5
#> 1: 1 1 1 9 1 1
#> 2: 2 1 1 1 1 1
#> 3: 3 4 1 0 9 1
#> 4: 4 5 1 1 1 1
#> 5: 5 1 1 9 1 1
Created on 2022-03-14 by the reprex package (v2.0.1)
dplyr
solution library(dplyr)
df %>% mutate(across(v2:v5, ~ ifelse(nchar(.x) > 1, 9, .x)))
#> id v1 v2 v3 v4 v5
#> 1 1 1 1 9 1 1
#> 2 2 1 1 1 1 1
#> 3 3 4 1 0 9 1
#> 4 4 5 1 1 1 1
#> 5 5 1 1 9 1 1
cols <- paste0("v", 2:5)
df[, cols] <- apply(df[, cols], c(1,2), function(x) ifelse(nchar(x) > 1, 9, x))
df
#> id v1 v2 v3 v4 v5
#> 1 1 1 1 9 1 1
#> 2 2 1 1 1 1 1
#> 3 3 4 1 0 9 1
#> 4 4 5 1 1 1 1
#> 5 5 1 1 9 1 1
Created on 2022-03-14 by the reprex package (v2.0.1)
A dplyr solution:
library(dplyr)
df1 %>% mutate(across(v2:v5, ~ifelse(nchar(.x)>1, 9, .x)))
#> # A tibble: 5 x 6
#> id v1 v2 v3 v4 v5
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 9 1 1
#> 2 2 1 1 1 1 1
#> 3 3 4 1 0 9 1
#> 4 4 5 1 1 1 1
#> 5 5 1 1 9 1 1
Created on 2022-03-13 by the reprex package (v2.0.1)
data
df1 <- structure(list(id = c(1, 2, 3, 4, 5), v1 = c(1, 1, 4, 5, 1),
v2 = c("1", "1", "1", "1", "1"), v3 = c("98", "1", "0", "1",
"90"), v4 = c("1", "1", "22", "1", "1"), v5 = c("1", "1",
"1", "1", "1")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-5L))
df <- data.frame(id,v1,v2,v3,v4,v5)
n <- NROW(df)
m <- NCOL(df)
for (j in 1:m) {
for (i in 1:n) {
ifelse(nchar(df[i,j]) > 1, df[i,j] <- 9, "")
}
}
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.