-2

enter image description here

How to separate text from numbers and turn text into column names?

TUSTLGC
  • 107
  • 7

1 Answers1

1

Based on your comment, I think the following gives you what you want.

Using data.table (but you could easily use base R):

library(data.table)
setDT(df)

df[, statistic := c("Min", "1st Q", "Median", "Mean", "3rd Q", "Max")]
setcolorder(df, "statistic")

cols <- names(df)[c(FALSE, rep(TRUE, ncol(df) - 1))]
df[, (cols) := lapply(.SD, function(x) str_replace(x, "^.*:\\s?", "") |> as.numeric()), 
  .SDcols = cols]
df

If this is not what you want, please edit your post with the output of dput(head(df)). In general, you should not post images of data or code - it makes your question much harder to answer.


As a toy example on some similar looking data:

df <- data.table(x = c("Min. : 2", "1st Q: 3", 
                       "Median.: 4", "Mean:5", 
                        "3rd Q: 6", "Max: 7"),
                 y = c("Min. : 3", "1st Q: 4",
                       "Median.: 5", "Mean: 6", 
                       "3rd Q: 7", "Max: 8"))
df
            x          y
1:   Min. : 2   Min. : 3
2:   1st Q: 3   1st Q: 4
3: Median.: 4 Median.: 5
4:     Mean:5    Mean: 6
5:   3rd Q: 6   3rd Q: 7
6:     Max: 7     Max: 8

The code above returns:

   statistic x y
1:       Min 2 3
2:     1st Q 3 4
3:    Median 4 5
4:      Mean 5 6
5:     3rd Q 6 7
6:       Max 7 8

You could make this more sophisticated by pulling out the exact text in the columns to make statistic, but this doesn't seem like a problem for your data.

diomedesdata
  • 995
  • 1
  • 6
  • 15