简体   繁体   English

根据数据帧的长度在列中交换两个条目

[英]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 我有一个数据框df其中说ab列,如果值的长度大于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. 但这没有用,我知道我必须使用类似df[length(df$a)]但我无法弄清楚。

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). PS:对于那些好奇的人,输入基本上是一个呼叫报告,有时在输入数据时,他们会交换单元号(10位数字)和ID号(4位数字)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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