如何在R中处理多个行标题?

8fq7wneg  于 2023-01-06  发布在  其他
关注(0)|答案(2)|浏览(202)

我有以下数据框:

fruit <- c("What is your favorite fruit?", "apple", "grape", "lemon")
color <- c("What is the color of the fruit?", "red", "purple", "yellow")
taste <- c("How does the fruit taste?", "sweet", "sweet", "sour")

df <- data.frame(fruit, color, taste)
View(df)

我希望前两行是标题。
理想情况下,我希望能够添加一个名为"number"的列,并且不需要第二个行标题。

df <- df %>%
  mutate(
    number = c(NA, 3, 7, 8)
  )

但是我不想在这里添加NA,最好这样做:

df <- df %>%
  mutate(
    number = c(3, 7, 8)
  )

并得到相同的df和,而不会得到Error inmutate():! Problem while computingnumber = c(3, 7, 8). ✖numbermust be size 4 or 1, not 3.错误。
在Excel中,我可以只隐藏第二行。R中有"隐藏"选项吗?

brccelvz

brccelvz1#

正如r2evens所建议的,调查问题通常以标签的形式存储。如果你的主要目标是如何保存数据元素,你也可以考虑使用列表。将数据框中的数据作为列表中的一个元素,将问题作为向量和列表中的另一个元素。
因此,将df视为 Dataframe ,将question视为问题向量。

number <- c(3,7,8)
fruit <- c("apple", "grape", "lemon")
color <- c("red", "purple", "yellow")
taste <- c("sweet", "sweet", "sour")

df <- data.frame(number, fruit, color, taste)

question <- c("What is your favorite fruit?", "What is the color of the fruit?", "How does the fruit taste?")

然后可以将它们合并到一个命名列表中。

myList <- list(df = df, question = question)

不是很漂亮

> myList
$df
  number fruit  color taste
1      3 apple    red sweet
2      7 grape purple sweet
3      8 lemon yellow  sour

$question
[1] "What is your favorite fruit?"    "What is the color of the fruit?" "How does the fruit taste?"

但是当你只想看到数据的时候,你可以这样做。

> myList$df
  number fruit  color taste
1      3 apple    red sweet
2      7 grape purple sweet
3      8 lemon yellow  sour

在这些情况下,你需要问题,你可以调用它们。在这个例子中,我用问题替换字段名,但是我必须首先删除数字列,除非我为该列放置保持器。

myListQ <-myList$df[-1] 
names(myListQ) <- myList$question
myListQ

> myListQ
  What is your favorite fruit? What is the color of the fruit? How does the fruit taste?
1                        apple                             red                     sweet
2                        grape                          purple                     sweet
3                        lemon                          yellow                      sour
yvt65v4c

yvt65v4c2#

碱R溶液:

# Rename the data.frame's vectors and add the 
# the number column: result_df => data.frame
result_df <- within(
  setNames(
    df[-1,],
    df[1,]
  ),
  {
    number = c(3, 7, 8)
  }
)

# Print the result to the console: 
# data.frame => stdout(console)
result_df

相关问题