R:向数据帧添加 0

The*_*ere 2 for-loop r dataframe

如何在 1990 年为源太阳能添加 0 量到下面的数据框中?1990 年的太阳能目前没有价值。

数据:

来源 数量
1990年 煤炭 19203
1990年 2345
1991年 煤炭 18490
1991年 2398
1991年 太阳的 123
1992年 ... ...
... ... ...
2019年 ... ...

代码:

data <- read.csv('annual_generation.csv')
data$source <- as.factor(data$source)
Run Code Online (Sandbox Code Playgroud)

这不起作用,但这是一般的想法:

for(i in 1990:2019) {
  for (j in data$source) {
    if (!data[i][j])
      data[i][j] = 0
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:根据下面的答案,这是最终的解决方案:

data <- complete(data, YEAR, STATE, ENERGY.SOURCE,
  fill = list(
    GEN = 0,
    TYPE.OF.PRODUCER = 'Total Electric Power Industry'))
Run Code Online (Sandbox Code Playgroud)
     YEAR STATE ENERGY.SOURCE TYPE.OF.PRODUCER                  GEN
     <int><fct> <fct>         <fct>                             <dbl>
  1  1990 IL    Coal          Total Electric Power Industry  54966018
  ...
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

我们可以使用completetidyr

library(tidyr)
complete(data, year, source, fill = list(amount = 0))
Run Code Online (Sandbox Code Playgroud)

-输出

# A tibble: 6 x 3
#   year source  amount
#  <int> <chr>    <dbl>
#1  1990 coal     19203
#2  1990 nuclear   2345
#3  1990 solar        0
#4  1991 coal     18490
#5  1991 nuclear   2398
#6  1991 solar      123
Run Code Online (Sandbox Code Playgroud)

另外,如果有一些'年份',缺少。我们可以使用一个范围

complete(data, year = 1990:2019, source, fill = list(amount = 0))
Run Code Online (Sandbox Code Playgroud)

数据

data <- structure(list(year = c(1990L, 1990L, 1991L, 1991L, 1991L), 
source = c("coal", 
"nuclear", "coal", "nuclear", "solar"), amount = c(19203L, 2345L, 
18490L, 2398L, 123L)), class = "data.frame", row.names = c(NA, 
-5L))
Run Code Online (Sandbox Code Playgroud)