You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在无1值的数据框列中随机插入1值(分种子)的R代码报错求助

Fixing Your Random 1 Insertion Code in R

Let's walk through fixing your code and getting the exact result you want—adding 3 random 1s to columns A, B, and D, each with a unique random seed.

Why Your Original Code Threw an Error

Your error Error in [<-data.frame (*tmp*, sample(nrow(x), 3), value = 1) : new columns would leave holes after existing columns comes from three key issues:

  1. Your method for identifying columns without 1s was incorrect (you were grabbing individual element positions instead of column indices).
  2. When assigning 1s in your function, you weren't targeting individual columns—you tried to overwrite entire rows, which confused R.
  3. Your function didn't return the modified data, so even if it worked, you wouldn't see the changes.

Corrected Code

Here's the revised code that does exactly what you need:

# Create your original data frame
df <- data.frame(
  A = rep(0, 10),
  B = rep(0, 10),
  C = c(0,1,0,0,0,1,0,1,0,0),
  D = rep(0, 10),
  E = c(0,1,0,1,0,0,0,0,0,0)
)

# Identify columns that have NO 1s (A, B, D)
no_one_cols <- which(colSums(df == 1) == 0)

# Function to add 3 random 1s per column with unique seeds
add_random_ones <- function(data, target_cols) {
  # Loop through each target column
  for (col_idx in target_cols) {
    # Set a unique seed for each column (using column index + 1 as you intended)
    set.seed(col_idx + 1)
    # Pick 3 random rows in this column
    random_rows <- sample(nrow(data), 3)
    # Assign 1 to those positions in the column
    data[random_rows, col_idx] <- 1
  }
  # Return the modified data frame
  return(data)
}

# Apply the function to get your modified data
df_updated <- add_random_ones(df, no_one_cols)

# Check the result
print(df_updated)

Key Improvements Explained

  • Correct Column Identification: colSums(df == 1) == 0 counts how many 1s are in each column, then we filter to columns with zero 1s—this gives us the exact columns we need to modify (A, B, D).
  • Column-Targeted Assignment: data[random_rows, col_idx] <- 1 explicitly targets the specific column and rows we want to update, avoiding the row-overwrite error.
  • Unique Seeds: Each column uses a unique seed (col_idx + 1), so the random positions for each column are reproducible and distinct.
  • Return Modified Data: The function returns the updated data frame, so you can save and use the result.

When you run this code, columns A, B, and D will each have exactly 3 random 1s, and the positions will stay consistent across runs thanks to the fixed seeds.

内容的提问来源于stack exchange,提问作者SAJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:44:36