Saurav
Saurav

Reputation: 597

Naming variable in R from a text File

I am very new to R and am looking for a possible solution for this problem.

Suppose I have a variables.txt file (or any other file for that matter), which contains a list of variable names. EX, Product, Ingredient, Label, Manufacturer, Marketing,

This text file is generated in java and this file has to be read in R and variable are to be named according to the names in the file.

My example code is : list(Product=0,Ingredient=0,Label=0,Manufacturer=0,Marketing=0)

which is now manually hard coded.

I need a way to get these names of variables from the variables.txt file and dynamically assign them in R. How can this be done?? is there any config file concept in R so that can also be a way out??

Upvotes: 0

Views: 1048

Answers (2)

Sören Pannier
Sören Pannier

Reputation: 69

If you need the list structure described above you can use any read.table or read.csv command to get the names into R as mthbnd showed above.

Say your file.txt looks like: Product,Ingredient,Label,Manufacturer,Marketing Read in the file and create a list from it. The Elements will then be filled with logical(0). Then you can easily set all elements to a 0 by using [ ] in order to keep the list structure

vars <- as.list(read.csv(file = "file.txt", header = T))
vars[] <- 0

Upvotes: 0

mthbnd
mthbnd

Reputation: 246

Maybe you can use:
data = read.table("file.txt",header=TRUE, sep=".") ?

The sep is depends on the seperator in the file. It could be comma, tab, space, dot or whatever.

With header=TRUE that means you want to take the original variable name from the file.

Upvotes: 1

Related Questions