根据存在条件将行添加到数据框 [英] Add row to dataframe based on presence criteria
问题描述
我正在尝试根据数据框架中的条件找到一种添加行的方法。我本来想要采取一个数据框架并插入缺少的值。这是我开始的:
I am trying to find a way to add rows based on criteria in a data frame. I essentially want to take a data frame and insert values that are missing. Here is what I start with:
Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L
我会就像搜索1A,2B和3A的Plot列的能力一样。由于1A存在,所以不会有任何动作,但2B和2B将被添加到数据帧中。对于缺少的值,我将始终想要输入绘图编号,而其他所有值都是0。最终结果如下:
I would like the ability to search the Plot column for 1A, 2B and 3A. Since 1A is present, there would be no action, but 2B and 2B would be added to the data frame. For missing values, I will always want to enter the Plot number and 0 for everything else. The end result looking like this:
Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L
2B 0 0
3A 0 0
推荐答案
使用合并
:
df <- read.table(text="Plot Species Status
1A ABBI L
1A PIEN D
1B ABBI D
1B PIEN L
2A ABBI L", header=TRUE, stringsAsFactors=FALSE)
lookfor <- data.frame(Plot=c("1A", "2B", "3A"), stringsAsFactors=FALSE)
res <- merge(df,lookfor,all=TRUE)
res[is.na(res$Species), c("Species", "Status")] <- 0
print(res)
# Plot Species Status
# 1 1A ABBI L
# 2 1A PIEN D
# 3 1B ABBI D
# 4 1B PIEN L
# 5 2A ABBI L
# 6 2B 0 0
# 7 3A 0 0
您应该考虑使用 NA
而不是 0
来表示缺失。
However, you should consider to use NA
instead of 0
to indicate missingness.
这篇关于根据存在条件将行添加到数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!