R:根据先前的行创建一个新行 [英] R: Creating a new row based on previous rows
本文介绍了R:根据先前的行创建一个新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是R的新手,正在尝试根据先前行中的值创建新行.
I'm new to R and trying to create a new row based on values on previous rows.
样本数据:
df <- data.table(Item = c("a", "b", "c", "d"),
"2010FY" = c(3, 5, 2, 2),
"2011FY" = c(5, 6, 2, 1),
"2012FY" = c(-1, 2, 2, 0.5))
我想创建一个新行,将第三行除以第四行.我们将此项目称为"e",理想情况下应这样:
I would like to create a new row that divides the 3rd row by the 4th row. Let's call this Item "e" and ideally should like this:
Item 2010FY 2011FY 2012FY
1 a 3 5 -1
2 b 5 6 2
3 c 2 2 2
4 d 2 1 0.5
5 e 1 2 4
使用dplyr,我的第一次尝试是:
Using dplyr, my first attempt is:
df <- bind_rows(df, e = df[Item %in% "c", ] / df[Item %in% "d", ])
这不起作用,因为字符不能被整除(即,项目"列).
This does not work because characters are not divisible (ie. The Item column).
我发现mutate_if函数可以工作,但只能按列工作.有没有办法我可以逐行执行此操作?
I found that the function mutate_if would work but only by column. Is there a way I can do this by row?
非常感谢您.
推荐答案
如上面的注释所指出的,这可行:
As pointed out in the comments above, this worked:
rbind(df, c(Item="e", df[df$Item == "c", -1] / df[df$Item == "d", -1]))
这篇关于R:根据先前的行创建一个新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文