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

是否存在R语言函数可实现指定DataFrame格式转换?

Transform Data to Variable-Value Pair Format in R

Absolutely! You can easily achieve this transformation using base R functions, and depending on your input structure, there are a couple of straightforward approaches. Let's walk through them:

Scenario 1: Your input is a character vector

Suppose your initial data is stored as a character vector like this:

original_data <- c("(p2)", "B", "D", "F", "36.0", "38.93", "36.06")

Follow these steps to get your desired format:

  1. Extract and clean the p2 value (remove the parentheses):
    p2 <- gsub(pattern = "\\(|\\)", replacement = "", x = original_data[1])
    
  2. Split the vector into the letter labels and numeric values:
    labels <- original_data[2:4]
    values <- original_data[5:7]
    
  3. Combine everything into the target structure, pairing each label with its value:
    result <- c(p2, "Col1", "Col2", as.vector(rbind(labels, values)))
    

If you print result, you'll get exactly what you want:

print(result)
# Output: "p2" "Col1" "Col2" "B" "36.0" "D" "38.93" "F" "36.06"

Scenario 2: Your input is a data frame row

If your data starts as a single-row data frame:

original_df <- data.frame(
  V1 = "(p2)", 
  V2 = "B", 
  V3 = "D", 
  V4 = "F", 
  V5 = 36.0, 
  V6 = 38.93, 
  V7 = 36.06,
  stringsAsFactors = FALSE
)

The process is similar—just extract the relevant columns first:

p2 <- gsub("\\(|\\)", "", original_df$V1)
labels <- unlist(original_df[, 2:4])
values <- unlist(original_df[, 5:7])
result <- c(p2, "Col1", "Col2", as.vector(rbind(labels, values)))

This will produce the same output vector as the first scenario.

Key functions used here:

  • gsub(): Cleans up the parentheses around p2
  • rbind(): Pairs each label with its corresponding value
  • as.vector(): Flattens the paired matrix into a single vector

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:00:24