R根据另一列中的值在多列之间进行更改。

huangapple go评论68阅读模式
英文:

R Make changes across multiple columns based off value in another column

问题

df1 <- df1 %>% mutate_at(vars(currentage, duestatus), ~if_else(birthdate == '1753-01-01', NA, .))

请注意,以上R代码将使用dplyr库的mutate_at函数将currentageduestatus列中的特定值更改为NA,仅当birthdate为'1753-01-01'时。如果birthdate不是'1753-01-01',它将保持不变。

英文:

I have a data frame where unknown birthdates are '1753-01-01'. The birthdates are used to calculate a current age and a due status. I'd like to change specific columns to NA if the birthdate is unknown and leave all others as is if the Birthdate is not unknown.

ID &lt;- c(&quot;001&quot;, &quot;002&quot;)
birthdate &lt;- c(&quot;1753-01-01&quot;, &quot;2019-01-10&quot;)
currentage &lt;- c(&quot;98659&quot;, &quot;1682&quot;)
duestatus &lt;- c(&quot;due&quot;, &quot;due&quot;)
gender &lt;- c(&quot;F&quot;, &quot;F&quot;)

df1 &lt;- data.frame(ID, birthdate, currentage, duestatus, gender)
df1
   ID  birthdate currentage duestatus gender
1 001 1753-01-01      98659       due      F
2 002 2019-01-10       1682       due      F

The desired output would be like this

   ID  birthdate currentage duestatus gender
1 001         NA         NA        NA      F
2 002 2019-01-10       1682       due      F

I have started playing with dplyr::mutate but just can't quite get it right. The birthdate is the only value that won't change, where as current_age and duestatus will change depending on the date the code is run so ideally the code would be based off something like: when the birthdate is '1753-01-01' then change birthdate, currentage and duestatus to NA

df1 &lt;- df1%&gt;% mutate(case_when(birthdate == &#39;1753-01-01&#39; ~ NA))

答案1

得分: 1

df1 %>%
  mutate(across(birthdate:duestatus, 
                ~if_else(birthdate == '1753-01-01', NA, .)))

Result

   ID  birthdate currentage duestatus gender
1 001       <NA>       <NA>      <NA>      F
2 002 2019-01-10       1682       due      F
英文:
df1 %&gt;%
  mutate(across(birthdate:duestatus, 
                ~if_else(birthdate == &#39;1753-01-01&#39;, NA, .)))

Result

   ID  birthdate currentage duestatus gender
1 001       &lt;NA&gt;       &lt;NA&gt;      &lt;NA&gt;      F
2 002 2019-01-10       1682       due      F

huangapple
  • 本文由 发表于 2023年2月14日 08:55:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442539.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定