0
0
R Programmingprogramming~20 mins

read.csv and write.csv in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
CSV Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this R code reading a CSV?

Consider the CSV file data.csv with content:

name,age
Alice,30
Bob,25

What will be the output of this R code?

R Programming
df <- read.csv('data.csv')
print(df$age[2])
A25
B30
CNULL
DError: object 'data.csv' not found
Attempts:
2 left
💡 Hint

Remember that read.csv reads the file into a data frame and $ accesses a column.

Predict Output
intermediate
2:00remaining
What does this code write to a CSV file?

Given this R code:

df <- data.frame(name=c('Tom','Jerry'), score=c(88, 92))
write.csv(df, 'scores.csv', row.names=FALSE)

What will the content of scores.csv be?

A
"name","score"
"Tom",88
"Jerry",92
B
"name","score"
Tom,88
Jerry,92
C
name,score
Tom,88
Jerry,92
DError: row.names argument invalid
Attempts:
2 left
💡 Hint

By default, write.csv adds quotes around strings and includes header.

🔧 Debug
advanced
2:00remaining
Why does this read.csv call fail?

What error does this code produce and why?

df <- read.csv('data.csv', header=FALSE)
print(df$age)

Assume data.csv has a header row with columns name and age.

R Programming
df <- read.csv('data.csv', header=FALSE)
print(df$age)
APrints the age column correctly
BError: object 'age' not found
CNULL because no column named 'age' exists without header
DSyntaxError due to missing comma
Attempts:
2 left
💡 Hint

When header=FALSE, column names default to V1, V2, ....

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error when writing CSV?

Which of these write.csv calls is syntactically invalid?

Awrite.csv(df, 'output.csv', row.names=FALSE)
Bwrite.csv(df, file='output.csv')
Cwrite.csv(df, file='output.csv', row.names=TRUE)
Dwrite.csv(df, file='output.csv' row.names=FALSE)
Attempts:
2 left
💡 Hint

Check commas between arguments.

🚀 Application
expert
2:00remaining
How many rows will this read.csv produce?

Given a CSV file data.csv with 5 rows of data plus 1 header row, what is the number of rows in df after this code?

df <- read.csv('data.csv', skip=2)
R Programming
df <- read.csv('data.csv', skip=2)
A4
B3
C5
D6
Attempts:
2 left
💡 Hint

The skip argument skips lines before reading header.