我该怎么走

df<-data.frame(id=c("A", "B", "B"), res=c("one", "two", "three"))
df

df.output<-data.frame(id=c("A", "B"), res1=c("one", "two"), res2=c(NA, "three"))
df.output

dplyr美元?

I do not know a priori the number of duplicates in id (in this example B has 2 occurrences), so the number of resX variables in the output data frame has 到 be generated on the fly.

推荐答案

您只需要创建一个行标识符,可以使用dplyr,然后使用tidyr::pivot_wider()生成所有resX个变量.

library(dplyr)
library(tidyr)

df %>%
  group_by(id) %>%
  mutate(
    no = row_number()
  ) %>%
  ungroup() %>%
  pivot_wider(
    id,
    names_from = no,
    names_prefix = "res",
    values_from = res
  )
#> # A tibble: 2 × 3
#>   id    res1  res2 
#>   <chr> <chr> <chr>
#> 1 A     one   <NA> 
#> 2 B     two   three

R相关问答推荐

生成具有受控相关性的x和y

对lme 4对象运行summary()时出错(diag中的错误(from,names = RST):对象unpackedMatrix_diag_get找不到)

如何在ggplot 2线性图的每个方面显示每个组的误差条?

根据R中两个变量的两个条件删除带有dspirr的行

将数据集中的值增加到当前包含的最大值

如何改变时间图R中的悬停信息?

如果某些列全部为NA,则更改列

使用rest从header(h2,h3,table)提取分层信息

在使用bslb和bootstrap5时,有没有办法更改特定dt行的 colored颜色 ?

打印XTS对象

将重复项转换为NA

将二进制数据库转换为频率表

SHINY:使用JS函数应用的CSS样式显示HTML表格

计算数据帧中指定值之前的行数,仅基于每行之后的future 行,单位为r

仅在R中的数据集开始和结束时删除所有 Select 列的具有NA的行

Conditional documentr::R中数据帧的summarize()

主题(Legend.key=Element_RECT(Fill=&Quot;White&Quot;))不起作用

Ggplot2如何找到存储在对象中的残差和拟合值?

roxygen2正在处理太多的文件

如何在访问之前下载的输入时同时上传和处理所有指定的shiny 输入?