我有这个 Dataframe df,我想用这个df来循环我的df 2;
Station_ID Station_Name
1 New York
2 London
3 Madrid
4 Rome
....
我有另一个 Dataframe df 2;
Station x1 x2
1 10 5
1 8 6
2 21 9
4 12 7
我想实现;
Station Station_Name x1 x2
1 New York 10 5
1 New York 8 6
2 London 21 9
4 Rome 12 7
到目前为止我所做的;
df2 <- df2 %>%
add_column(Station_Name = NA)
for (i in 1:nrow(df2$Station_Name)) {
if (df$Station_ID == df2$Station) {
df2$Sitation_Name <- df$Station_Name
}
}
1:nrow(df2 $站点名称)中出错:长度为0的参数
我也很好奇,如果我有5个不同的 Dataframe ,我建议我怎么做,我必须写一个循环,遍历所有这些不同的 Dataframe ,添加它们相应的名称?
3条答案
按热度按时间kd3sttzy1#
自然的方法是使用
left_join
而不是循环:或者使用R为基数:
数据
s8vozzvw2#
作为Stefan,我也建议在这里使用
dplyr
。如果你仍然想做循环,这将是我的解决方案:创建于2022年12月25日,使用reprex v2.0.2
您遇到的问题是,
df$Station_Name
实际上只是一个向量,因此无法应用nrow()
。2nbm6dog3#
使用
data.table