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

如何在R中通过向量名称与列名模糊匹配填充DataFrame?

Solution

Here's a concise base R approach to map your vectors to the DataFrame columns by matching substrings between column names and vector element names:

# Initialize your data
df <- data.frame(matrix(NA, ncol = 3, nrow = 4))
colnames(df) <- c("AA", "BB", "CC")

vec1 <- c(1, 2, 3)
names(vec1) <- c("BB745", "456AA", "123CC3")

vec2 <- c(4, 5, 6)
names(vec2) <- c("BB745", "456AA", "123CC3")

# Function to map a vector to the df column order (reusable for multiple vectors)
map_vector_to_df <- function(vec, target_cols) {
  sapply(target_cols, function(col) vec[grepl(col, names(vec))])
}

# Fill the first two rows
df[1, ] <- map_vector_to_df(vec1, colnames(df))
df[2, ] <- map_vector_to_df(vec2, colnames(df))

# Check the result
df

Output:

AA BB CC
1  2  1  3
2  5  4  6
3 NA NA NA
4 NA NA NA

How it works:

  • The map_vector_to_df function uses sapply to loop through each column name in your DataFrame.
  • For each column name, grepl(col, names(vec)) identifies which element name in the vector contains the column name as a substring.
  • We extract the corresponding value from the vector and arrange it to match the DataFrame's column order.
  • Assigning these results to df[1, ] and df[2, ] fills your desired rows with the correct values.

If you prefer an even more compact version (using R 4.1+ lambda syntax), you can skip the function and write directly:

df[1,] <- sapply(colnames(df), \(x) vec1[grepl(x, names(vec1))])
df[2,] <- sapply(colnames(df), \(x) vec2[grepl(x, names(vec2))])

This method is lightweight, uses only base R, and assumes each column name matches exactly one element name in the vectors (which aligns with your example).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:43:10