df <- data.frame(a = 1:10, b = 21:30, c = 31:40)
library(purrr)
imap(df, ~paste0("The name is ", .y, " and the sum is ", sum(.x)))
# $a
# [1] "The name is a and the sum is 55"
#
# $b
# [1] "The name is b and the sum is 255"
#
# $c
# [1] "The name is c and the sum is 355"
这只是编写以下Base R代码的一种更方便的方法,它给出了相同的输出:
Map(function(x, y) paste0("The name is ", y, " and the sum is ", sum(x))
, df, names(df))
# Simulating your data
a <- c(1,2,3)
b <- c(4,5,6)
df <- data.frame(a, b)
# Answer 1
for (i in 1:ncol(df)){
print(names(df)[i]) # acessing the name of column
print(df[,i]) # acessing column content
print('----')
}
或者这个替代方案:
# Answer 2
columns <- names(df)
for(i in columns) {
print(i) # acessing the name of column
print(df[, i]) # acessing column content
print('----')
}
4条答案
按热度按时间frebpwbc1#
2exbekwf2#
就这么做
打印
df
中的所有列名。不需要循环,除非您想对每一列执行更详细的操作。如果需要第i个列名:
xt0899hw3#
您可以使用
purrr
包中的imap
函数来代替循环。在编写代码时,.x
是对象,.y
是名称。这只是编写以下Base R代码的一种更方便的方法,它给出了相同的输出:
u3r8eeie4#
您可以尝试以下代码:
或者这个替代方案:
希望有帮助!