Home > Software design >  is it possible to make a looping statement in R wherein it will turn all column title of a dataframe
is it possible to make a looping statement in R wherein it will turn all column title of a dataframe

Time:10-02

I have a large data frame. I want to make a looping statement wherein it will assign each column of the dataframe into a varible named after its column title.

In the code I created, when I type name[1] in the console before performing the looping statement, it shows the name of the column, for example "Company". However if I use it in a looping statement, instead of using "Company" as the variable name, it uses "name[1]".

This is the code I created

df = read.csv('fileName.csv')
a = 0
b = 1
while (a!=ncol(df) 1){
  name = colnames(df)
  name[b] = df[b]
  a = a 1
  b = b 1
}

e.g

col1     col2      col3
 1       pizza     coke
 2       burger    pepsi
 3       fries     sprite

Output: When you type 'col1' on the console, its data will show. Instead of using df[1].

The variable will hold the data of the column based in the dataframe. Instead of manually coding

col1 = df[1]
col2 = df[2]
col3 = df[3]

it will be very exhaustive especially on the data frame I use that have almost 100 column title.

CodePudding user response:

You may use list2env to convert each column of df to a separate object in the global environment. This is normally not advised, but if you need to do it, you can do the following:

list2env(df,envir = .GlobalEnv)

Running this on the above example frame (df), will result in three new objects in your global environment: col1, col2, and col3. For example:

> col2
[1] "pizza"  "burger" "fries" 
  •  Tags:  
  • r
  • Related