R语言中为kirp数据框添加行并命名为sample时遇报错如何解决?
Why the Error Occurs
Your code attempts to modify rownames on the temporary subset returned by tail(kirp, n=1)—this doesn't reference the original data frame, and R doesn't support direct assignment to tail() output (hence the "could not find function 'tail<-'" error). Additionally, your first line has a syntax error (an extra closing parenthesis).
Fixed Code (Direct Row Assignment)
Correct the syntax issue and assign the rowname directly using the new row's index:
# Add the new row (remove the extra closing parenthesis) kirp[nrow(kirp) + 1, ] <- "KIRP" # Set rowname for the newly added row rownames(kirp)[nrow(kirp)] <- "sample"
More Robust Approach (Using rbind)
For cleaner code and to avoid potential data type mismatches, create a new row as a data frame and bind it to the original:
# Create new row with the desired rowname new_row <- data.frame(t("KIRP"), row.names = "sample") # Merge with the original data frame kirp <- rbind(kirp, new_row)
Note: t() transposes the vector to match your data frame's column structure. Adjust this step if your data frame has multiple columns with mixed data types.
Verify the Result
Confirm the new row is added correctly with:
tail(kirp, n=1)
内容的提问来源于stack exchange,提问作者Anon

