基于不同 Dataframe 中的另一列使用for循环填充空列

14ifxucb  于 2022-12-27  发布在  其他
关注(0)|答案(3)|浏览(135)

我有这个 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 ,添加它们相应的名称?

kd3sttzy

kd3sttzy1#

自然的方法是使用left_join而不是循环:

library(dplyr)

df2 <- left_join(df2, df, by = c("Station" = "Station_ID"))

df2
#>   Station x1 x2 Station_Name
#> 1       1 10  5     New York
#> 2       1  8  6     New York
#> 3       2 21  9       London
#> 4       4 12  7         Rome

或者使用R为基数:

df2 <- merge(df2, df, by.x = "Station", by.y = "Station_ID", all.x = TRUE)

df2
#>   Station x1 x2 Station_Name
#> 1       1 10  5     New York
#> 2       1  8  6     New York
#> 3       2 21  9       London
#> 4       4 12  7         Rome

数据

df <- structure(list(Station_ID = 1:4, Station_Name = c(
  "New York",
  "London", "Madrid", "Rome"
)), class = "data.frame", row.names = c(
  NA,
  -4L
))

df2 <- structure(list(Station = c(1L, 1L, 2L, 4L), x1 = c(
  10L, 8L, 21L,
  12L
), x2 = c(5L, 6L, 9L, 7L)), class = "data.frame", row.names = c(
  NA,
  -4L
))
s8vozzvw

s8vozzvw2#

作为Stefan,我也建议在这里使用dplyr。如果你仍然想做循环,这将是我的解决方案:

#Loop
df <- data.frame(Station_ID= c(1:4),
                 Station_Name= c("NY", "Lon", "Mad", "Rome"))

df2 <- data.frame(Station= c(1:4),
                  X1= c(10,8,21,12),
                  X2= c(5,6,9,7))


for (i in 1:nrow(df2)) {
 
  df2$Station_Name[i] <- df$Station_Name[i]
  
}

df2
#>   Station X1 X2 Station_Name
#> 1       1 10  5           NY
#> 2       2  8  6          Lon
#> 3       3 21  9          Mad
#> 4       4 12  7         Rome

创建于2022年12月25日,使用reprex v2.0.2
您遇到的问题是,df$Station_Name实际上只是一个向量,因此无法应用nrow()

2nbm6dog

2nbm6dog3#

使用data.table

library(data.table)
setDT(df2)[df, on = .(Station = Station_ID), nomatch = FALSE]
   Station x1 x2 Station_Name
1:       1 10  5     New York
2:       1  8  6     New York
3:       2 21  9       London
4:       4 12  7         Rome

相关问题