writer_typer
writer_typer

Reputation: 798

How to loop through a dataframe and get value of corresponding column?

I'm trying to loop through a dataframe and get values of two columns. But they get printed twice.

df <- tribble(
  ~x, ~y, 
  "a", 2,  
  "b", 1
)
for(i in df) {
  print(paste(df$x, "occurs", df$y, "time[s]"))
}

Output

[1] "a occurs 2 time[s]" "b occurs 1 time[s]"
[1] "a occurs 2 time[s]" "b occurs 1 time[s]"

How do I make it print only once and in a new line?

Upvotes: 1

Views: 772

Answers (3)

writer_typer
writer_typer

Reputation: 798

A combined answer inspired by @Park and @Ronak Shah:

writeLines(paste(df$x, "occurs", df$y, "time[s]"), sep = "\n")
a occurs 2 time[s]
b occurs 1 time[s]

Upvotes: 1

Kra.P
Kra.P

Reputation: 15123

Use writeLines function

for(i in 1:dim(dummy)[1]) {
  writeLines((paste(dummy$x[i], "occurs" , dummy$y[i], "time[s]", "\n")))
}

result:

a occurs 2 time[s] 

b occurs 1 time[s] 

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

Iterate over the rows of the dataframe and use it to subset the dataframe to get every row output separately.

for(i in seq(nrow(df))) {
  print(paste(df$x[i], "occurs", df$y[i], "time[s]"))
}

#[1] "a occurs 2 time[s]"
#[1] "b occurs 1 time[s]"

As I understand this is just an example to do something else, otherwise paste is vectorised and you'll not need loop to just print the content. This can work directly.

paste(df$x, "occurs", df$y, "time[s]")

Upvotes: 1

Related Questions