当dataframe列不包含特定级别时,如何强制执行该级别?(使用R)

当dataframe列不包含特定级别时,如何强制执行该级别?(使用R),r,levels,R,Levels,我在数据集中有可能包含0或1的列,但有些列只包含0 我想使用这些数字作为因子,但我仍然希望每列都有0和1级。我尝试下面的代码,但我不断得到一个错误,但我不明白为什么 #dataframe df has 100 rows column_list = c("col1", "col2", "col3") for (col in column_list) { #convert number 0 and number 1 to factors # (but sometim

我在数据集中有可能包含0或1的列,但有些列只包含0

我想使用这些数字作为因子,但我仍然希望每列都有0和1级。我尝试下面的代码,但我不断得到一个错误,但我不明白为什么

#dataframe df has 100 rows

column_list = c("col1", "col2",  "col3")  

for (col in column_list) {
      #convert number 0 and number 1 to factors
      # (but sometimes the data only has zeros)
      df[,col] <- as.factor(df[,col])

      # I want to force levels to be 0 and 1
      # this is for when the data is completely missing number 1

      levels(df[, col] <- c(0,1))          #give error

      # Error in `[<-.data.frame`(`*tmp*`, , col, value = c(0, 1)) : 
      # replacement has 2 rows, data has 100


      print(levels(df[, col]))
      #this produces "0" "1" or just "0" depending on the column

}
#数据帧df有100行
列列表=c(“列1”、“列2”、“列3”)
用于(列列表中的列){
#将数字0和数字1转换为系数
#(但有时数据只有零)

df[,col]如果您指出错误所在,则该行写得不正确。它应该是:

df[, col] <- factor(df[, col], levels = c(0,1)

df[,col]我想你刚才把
放错地方了

这项工作:

column_list = c("col1", "col2",  "col3")  
df <- data.frame(matrix(0, nrow = 100, ncol = 3))
names(df) <- column_list

for (col in column_list) {
  #convert number 0 and number 1 to factors
  # (but sometimes the data only has zeros)
  df[,col] <- as.factor(df[,col])

  # I want to force levels to be 0 and 1
  # this is for when the data is completely missing number 1

  levels(df[, col]) <- c(0,1)          #no error anymore

  # Error in `[<-.data.frame`(`*tmp*`, , col, value = c(0, 1)) : 
  # replacement has 2 rows, data has 100


  print(levels(df[, col]))
  #this produces "0" "1" or just "0" depending on the column

}
column\u list=c(“col1”、“col2”、“col3”)
谢谢!级别(df[,col])
column_list = c("col1", "col2",  "col3")  
df <- data.frame(matrix(0, nrow = 100, ncol = 3))
names(df) <- column_list

for (col in column_list) {
  #convert number 0 and number 1 to factors
  # (but sometimes the data only has zeros)
  df[,col] <- as.factor(df[,col])

  # I want to force levels to be 0 and 1
  # this is for when the data is completely missing number 1

  levels(df[, col]) <- c(0,1)          #no error anymore

  # Error in `[<-.data.frame`(`*tmp*`, , col, value = c(0, 1)) : 
  # replacement has 2 rows, data has 100


  print(levels(df[, col]))
  #this produces "0" "1" or just "0" depending on the column

}