Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Using data frame column names as vector names

Tags:

r

I am a fairly new R user (MATLAB convert) and am trying to name the variables in my data set using the column names that I've given the data set.

Let's say I've got a data frame called Z with three columns that I have named as below.

Header <- c("Date", "Time", "Data")
colnames(Z) <- Header

Is there a simple way to convert these column names to vector names so that when I type "Data" in the command line, the values from column 3 appear (and so I can call these names easily in a script)?

Thanks much in advance!

like image 794
Dan_Alexander Avatar asked Apr 25 '26 01:04

Dan_Alexander


1 Answers

Here is an example of attach and detach functions with your data. I believe this is ok for interactive use, but it´s not best practice for programming. Probably, it´s not really recomendable to use at all, i believe i´ve never used it!

Z <- data.frame(matrix(rpois(9, 80), ncol = 3, nrow = 9))
head(Z)
> head(Z)
X1  X2  X3
1  69  69  69
2  80  80  80
3  69  69  69
4 103 103 103
5  65  65  65
6  81  81  81

# Use different names for each column!

Header <- c("Date_1", "Time", "Data_2")
colnames(Z) <- Header

head(Z)
 Date_1 Time Data_2
1   69   69   69
2   80   80   80
3   69   69   69
4  103  103  103
5   65   65   65
6   81   81   81


attach(Z)

Date_1
[1]  69  80  69 103  65  81  84  70  93

Time
[1]  69  80  69 103  65  81  84  70  93

detach(Z)

# Do not forget to detach! 
Time
Error: objeto 'Time' no encontrado

Perhaps another option is using with:

with(Z, Time)
# [1] 91 81 81 87 82 72 81 74 85

with(Z, quantile(Time))
#  0%  25%  50%  75% 100% 
#  72   81   81   85   91 

Or just subsetting each variable.

# Subsetting keeping attributes
Z[2]
Z["Time"]

attributes(Z["Time"])
# $names
# [1] "Time"

# $class
# [1] "data.frame"

# $row.names
# [1] 1 2 3 4 5 6 7 8 9

# Subsetting droping attributes
Z$Time
Z[["Time"]]

attributes(Z[["Time"]])
# NULL
like image 77
marbel Avatar answered Apr 26 '26 13:04

marbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!