将数据框中的值替换为另一列中的值

将数据框中的值替换为另一列中的值

本文介绍了根据第三列上的条件,将数据框中的值替换为另一列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我的数据框:class columnAfoo 10bar 14.2hello 48695bar 4foo -7我试着执行以下操作:if (my_df$class== "foo") { my_df$columnB <- my_df$columnA * 2}else{ if (my_df$class == "bar") { my_df$columnB <- my_df$columnA * 5 }else{ my_df$columnB <- my_df$columnA * 10 }}编辑:我也尝试过:ifelse (my_df$class== "foo", my_df$columnB <- my_df$columnA * 2 ifelse (my_df$class== "bar", my_df$columnB <- my_df$columnA * 5, my_df$columnB <- my_df$columnA * 10 ))不用工作,让我以伪代码的形式说明:As it doesn't work, let me state it in pseudo-code :for each row, if the value in column class is "foo" set the value in column B to be 2 times the value in column A if the value in column class is "bar" set the value in column B to be 5 times the value in column A if the value in column class is something else set the value in column B to be 10 times the value in column A我的问题当然是分配运算符:如果我使用 整个 columnB 列最后是 columnA 乘以 5 (因为这样发生 class 最后一行的值为 bar )。My problem is, of course, with the assigning operator : if I use <- the whole columnB column ends up being columnA multiplied by 5 (because it so happens that the class value of the last row is bar).任何解决方案?我将采取一种解决方案来解决我的问题,而不必经过 if / elseif / else 语法,但是如果有人可以提供解决方案来保护这种语法,我也会非常感激,为了学习。I'll take a solution that solves my problem without going through this if/elseif/else syntax, but I'd also really appreciate it if someone could provide a solution keeping this syntax, for the sake of learning.谢谢推荐答案 如果不是矢量化的,所以你可以尝试使用 ifelseif isnt vectorised so you can try to use ifelse / p>for examplemy_df$columnB=ifelse(my_df$class== "foo",my_df$columnA * 2, ifelse(my_df$class == "bar",my_df$columnA * 5,my_df$columnA * 10)) 这篇关于根据第三列上的条件,将数据框中的值替换为另一列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-14 22:50