簡體   English   中英

基於不同數據框中的另一列,使用 for 循環填充空列

[英]filling an empty column with a for loop based on another column in a different data frame

我有這個數據框 df,我想用這個 df 循環遍歷我的 df2;

Station_ID    Station_Name
1             New York
2             London
3             Madrid
4             Rome
....

我有另一個數據框 df2;

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$Station_Name) 中的錯誤:長度為 0 的參數

也只是好奇,如果我有 5 個不同的數據幀,我會建議我怎么做,我必須編寫一個循環,將 go 通過所有這些不同的數據幀來添加它們相應的名稱?

代替循環的自然方法是使用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)

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
))

作為 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()

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM