-2

I want to modify my data frame in R. My current data frame is:

df <- data.frame(ID = c(1, 2, 3), A = c(10, 20, 30), B = c(0, 0, 1)) 

df_transposed <- df %>% pivot_longer(cols = -ID, names_to = "Variable", values_to = "Value") %>% pivot_wider(names_from = ID, values_from = Value)

I need modify my data frame to the follow form:

row   A  X1_cen   B   X2_cen ....
X1    10   0      11  1    
X2    12   0      13  0

I need the code in R to modify my dataframe. The packages and more :)

Mark
  • 7,785
  • 2
  • 14
  • 34
Boris
  • 1
  • 1
  • 3
    Please include your example data as code we can load. That makes it easier for people to help you, and by reducing ambiguity makes it more likely you'll see solutions that actually work for you. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Jon Spring Jun 19 '23 at 22:05
  • 1
    You're looking for a combination of subsetting and a transpose. See this article: https://www.statology.org/dplyr-transpose/ – David Jun 19 '23 at 23:19
  • This is my current problem, the code is: Example data frame df <- data.frame(ID = c(1, 2, 3), A = c(10, 20, 30), B = c(0, 0, 1)) Transpose the data frame df_transposed <- df %>% pivot_longer(cols = -ID, names_to = "Variable", values_to = "Value") %>% pivot_wider(names_from = ID, values_from = Value) But I need the information of B in columns in the right of 1, 2, and 3. – Boris Jun 21 '23 at 12:19

1 Answers1

0

This is what (it sounds like) you want:

df %>% pivot_longer(cols = -ID, names_to = "Variable", values_to = "Value") %>% 
    mutate(ID = paste0(Variable, "_", ID) ) %>%
    select(-Variable) %>%
    pivot_wider(names_from = ID, values_from = Value)

# A tibble: 1 × 6
    A_1   B_1   A_2   B_2   A_3   B_3
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1    10     0    20     0    30     1

Keep in mind that putting two variables into your column names is extremely poor data practices, so if you're using this for any real world application I would caution against it

Mark
  • 7,785
  • 2
  • 14
  • 34