Abhijit Balki
Abhijit Balki

Reputation: 23

Get Column Name of CSV file

I want to get column Names of CSV data and apply some functions on column name.

I tried the following code, but the output just returns data type

reading_data <- read.csv("test.csv")

print("Header Row:")
print(reading_data[0,])  # This gives me a list of column names correctly
print(class(reading_data[0,])) # O/P is: "data.frame"
print("++++++++++++++++++++++++++++")
for(i in 1:ncol(reading_data)){ 
    print(reading_data[0,i]) # O/P is: numeric(0) ; I want string value of data name here.
} 

Upvotes: 1

Views: 3467

Answers (3)

Abhijit Balki
Abhijit Balki

Reputation: 23

Thanks for the answers.

names(reading_data) served my purpose.

col_names = names(reading_data)

for(i in 1:length(col_names)){ 
  print(col_names[i]) 
  # Operation on col_names[i]
} 

PS: I am a newbie in R, so do not know all these basic functions :)

Upvotes: 1

rg255
rg255

Reputation: 4169

The way to get column names is not reading_data[0,] but rather use the colnames() function... in this case, colnames(reading_data).

If you want these stored in a vector use

colnames_df <- colnames(reading_data)

Which you could apply your function to (you can also apply it directly to colnames(reading_data)).

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388817

reading_data[0,] doesn't return you the column names, it returns you a dataframe with no rows selected.

Check for example with mtcars

mtcars[1, ]
#          mpg cyl disp  hp drat   wt  qsec vs am gear carb
#Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4

This is 1st row of mtcars with column names.

Now if you do mtcars[0, ]

mtcars[0, ]
# [1] mpg  cyl  disp hp   drat wt   qsec vs   am   gear carb
#<0 rows> (or 0-length row.names)

It returns column names as it is with no rows selected as there is no row at index 0.

If you want to apply some functions on each column name separately you can do

for(i in names(reading_data)){ 
    print(i) 
    #add the operation to be applied here
} 

names(mtcars) or colnames(mtcars) would give you the column names directly.

names(mtcars)
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"
colnames(mtcars)
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

Upvotes: 2

Related Questions