Home > Net >  Making new data frame in R
Making new data frame in R

Time:10-15

Say, I have a data table with three columns: apples, orange, and age. What code I can write in R to make the other one with upper case: FRUITS, AGE, USE

apple orange age FRUITS AGE USE
3 2 1-3 - - apple 1-3 3
4 5 4-6 - - apple 4-6 4
8 9 7-9 - - apple 7-9 8
- - orange 1-3 2
- - orange 4-6 5
- - orange 7-9 9

This is an example so I gives fewer values, but let's say my data have 30 rows like that. I do not want to manually add each rows into a new data frame. how can I turn the apples and oranges into FRUITS and make a column use?

CodePudding user response:

I think using the pivot_longer() tidy function moodymudskipper suggested it would be coded like this

library(tidyr)
new_data <- data %>%
pivot_longer(!age, names_to = "FRUITS", values_to = "USE")%<%
select_all(toupper)

CodePudding user response:

One possible way to solve your problem

library(data.table)

melt(as.data.table(df), 
     measure=c("apple", "orange"), 
     variable.name="FRUITS", 
     value.name="USE")
  •  Tags:  
  • r
  • Related