简体   繁体   中英

Swap two entry in a column based on the length in a data frame

I have a dataframe df with say column a and b , I want to swap values between the column if the length of a value is more than 3

Input:

a       b
1       23
2       44
3       43324
4       76

Expected Output:

a      b
1      23
2      44
43324  3
4      76

I was thinking of something like the below:

df <- transform(df, df$a = ifelse(length(df$b) > 3, a, b), df$a = ifelse(length(df$b) > 3, b, a))

But this did not work, I know I have to use something like df[length(df$a)] but I am not able to figure this out.

PS: For those who are curious, the input is basically a call report, sometimes while entering data, they swap the cell number (10 digit) and the ID number (4 digits).

Here is a one liner

df[nchar(df$b)>3, c("a", "b")] <- df[nchar(df$b)>3, c("b", "a")]
> df
#      a  b
#1     1 23
#2     2 44
#3 43324  3
#4     4 76

Perhaps you could build a custom function that works for your example:

swap <- function(df) {

  a <- ifelse(nchar(df$b) > 3, df$b, df$a)
  b <- ifelse(nchar(df$b) > 3, df$a, df$b)
  df$a <- a
  df$b <- b

return(df)

}

#Let's test it
swap(df)
#      a  b
#1     1 23
#2     2 44
#3 43324  3
#4     4 76

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM