Lenny
Lenny

Reputation: 29

R concatenate a column of dataframe, make a vector, then use it in a for loop

I have a data frame that looks like this:

Tote_Type Length Width Height
L1        36     24     24
L2        33     20     20
M1        30     18     18
M2        27     16     16
S1        24     14     14
S2        20     10     10

I want to make a highly automated program. This dataframe is an input data. I will read in this dataframe from an excel file. Then I will loop through tote types like this

for (i in c("L1", "L2", "M1", "M2", "S1", "S2")){
    pass
}

The problem is, the tote types may change. I want to create a tool that does not need to edit R code. All the changes need to be done in Excel.

So my goal is read in an excel file as a dataframe that looks like the above, then use the first column data or part of first column data to create a vector like c("L1" , "L2" , "M1", "M2", "S1", "S2"), then apply this vector to the for loop.

I really don't know how to achieve this. Any help would be appreciated. Thank you.

Upvotes: 0

Views: 73

Answers (1)

f.lechleitner
f.lechleitner

Reputation: 3812

Is this what you're looking for? You can create the vector using unique(). Lets create the data frame first:

df <- read.table(
  text = "
  Tote_Type Length Width Height
  L1        36     24     24
  L2        33     20     20
  M1        30     18     18
  M2        27     16     16
  S1        24     14     14
  S2        20     10     10
  ",
  header = T,
  stringsAsFactors = F
)

Unique gives your desired vector:

> unique(df$Tote_Type)
[1] "L1" "L2" "M1" "M2" "S1" "S2"

The loop:

for (i in unique(df$Tote_Type)){
  print(i)
}

Output:

[1] "L1"
[1] "L2"
[1] "M1"
[1] "M2"
[1] "S1"
[1] "S2"

Upvotes: 1

Related Questions