Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:基于变量名中的字符串将数值数据从列透视到行_R_Function_Pivot - Fatal编程技术网

R:基于变量名中的字符串将数值数据从列透视到行

R:基于变量名中的字符串将数值数据从列透视到行,r,function,pivot,R,Function,Pivot,我有一个数据集,我想根据变量名是否包含任何字符串将其转换为长格式:list_a将名称指定为长格式,而将名称指定为长格式 -输出 # A tibble: 3 x 5 # date grp usd eur gbp # <chr> <chr> <dbl> <dbl> <dbl> #1 2020-12-31 a 1000 100 10 #2 2020-12-31 b 200

我有一个数据集,我想根据变量名是否包含任何字符串将其转换为长格式:list_a将名称指定为长格式,而将名称指定为长格式

-输出

# A tibble: 3 x 5
#  date       grp     usd   eur   gbp
#  <chr>      <chr> <dbl> <dbl> <dbl>
#1 2020-12-31 a      1000   100    10
#2 2020-12-31 b      2000   200    20
#3 2020-12-31 c      3000   300    30
将名称_sep指定为名称_toin pivot _更长

-输出

# A tibble: 3 x 5
#  date       grp     usd   eur   gbp
#  <chr>      <chr> <dbl> <dbl> <dbl>
#1 2020-12-31 a      1000   100    10
#2 2020-12-31 b      2000   200    20
#3 2020-12-31 c      3000   300    30
使用“重塑”的基本R选项

给予

使用“重塑”的基本R选项

给予


谢谢你的回答,这个选项最适合我的需要!谢谢你的回答,这个选项最适合我的需要!谢谢,此选项有效,但提供的另一个答案对我的真实数据集更有效。@Rosie无需担心,只选择适合您的用例的答案。谢谢,此选项有效,但提供的另一个答案对我的真实数据集更有效。@Rosie无需担心,只选择适合您的用例的答案。
library(dplyr)
df %>%
   pivot_longer(cols = -date, names_to = c("grp", ".value"), names_sep = "_")
# A tibble: 3 x 5
#  date       grp     usd   eur   gbp
#  <chr>      <chr> <dbl> <dbl> <dbl>
#1 2020-12-31 a      1000   100    10
#2 2020-12-31 b      2000   200    20
#3 2020-12-31 c      3000   300    30
reshape(
  setNames(df, gsub("(\\w+)_(\\w+)", "\\2.\\1", names(df))),
  direction = "long",
  varying = -1
)
          date time  usd eur gbp id
1.a 2020-12-31    a 1000 100  10  1
1.b 2020-12-31    b 2000 200  20  1
1.c 2020-12-31    c 3000 300  30  1