[R] use value in variable to be name of another variable
David L Carlson
dcarlson at tamu.edu
Tue Jul 12 17:21:27 CEST 2016
It appears that you are just trying to use the first row to create a column name for the rest of the column. If that is all you are doing something like this is quicker, but it uses the data frame.
> set.seed(42)
> tTargTFS <- data.frame(matrix(replicate(100, paste0(sample(LETTERS, 6), collapse="")), 10), stringsAsFactors=FALSE)
> New <- tTargTFS[ -1, ]
> colnames(New)
[1] "X1" "X2" "X3" "X4" "X5" "X6" "X7" "X8" "X9" "X10"
> colnames(New) <- tTargTFS[1, ]
> colnames(New)
[1] "XZGTOK" "RYSNXD" "JKNXPI" "XVHFQP" "BOZEMK" "MLBHTV" "OQGWZM" "CMXSLB" "GOUDTJ"
[10] "SYMEXP"
> str(New)
'data.frame': 9 obs. of 10 variables:
$ XZGTOK: chr "TDPQKX" "YGLVWC" "MOVDXT" "CMJUXR" ...
$ RYSNXD: chr "HUQFAC" "FLEQAH" "NAZDHX" "UOFCBG" ...
$ JKNXPI: chr "XYFQTM" "QXUNSC" "TPDBKQ" "TUEVGD" ...
$ XVHFQP: chr "XTDGEQ" "DZBXLC" "TSVLYJ" "ELXYFV" ...
$ BOZEMK: chr "EDLVHY" "HNASCL" "OPRCGT" "NDUEXS" ...
$ MLBHTV: chr "KDHXCU" "MCFVGN" "XYKJDF" "OXITPV" ...
$ OQGWZM: chr "QXJGBW" "TCRWEY" "BUNKIF" "PUCWDB" ...
$ CMXSLB: chr "MIQLWV" "LCWAJE" "CMPVHR" "HLDSOB" ...
$ GOUDTJ: chr "XGCBVK" "VKLEQG" "EADZLR" "CWNDTF" ...
$ SYMEXP: chr "RFIHTE" "RDCXUF" "XTYEBA" "HIRFLP" ...
-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352
-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Matthew
Sent: Monday, July 11, 2016 5:34 PM
To: Rolf Turner
Cc: r-help at r-project.org
Subject: Re: [R] use value in variable to be name of another variable
Hi Rolf,
Thanks for the warning. I think because my initial efforts used the
assign function, that Jim provided his solution using it.
Any suggestions for how it could be done without assign() ?
Matthew
On 7/11/2016 6:31 PM, Rolf Turner wrote:
> On 12/07/16 10:13, Matthew wrote:
>> Hi Jim,
>>
>> Wow ! And it does exactly what I was looking for. Thank you very
>> much.
>>
>> That assign function is pretty nice. I should become more familiar
>> with it.
>
> Indeed you should, and assign() is indeed nice and useful and handy.
> But it should be used with care and circumspection. It *alters the
> global environment* which is fraught with peril. Generally speaking
> most things that can be done with assign() (and its companion function
> get()) are better and more safely done using lists and functions and
> other "natural" R-ish constructs. Resist the temptation to turn R into
> a macro language.
>
> cheers,
>
> Rolf Turner
>
______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list