假设我们有一个包含数值的数据框,它看起来像:
Temperature Height
32 157
31 159
33 139
我想用 Height
、pic_00001
等替换 pic_00002
值,以便最终结果是:
Temperature Height
32 pic_00001
31 pic_00002
33 pic_00003
完整数据框中有 10,000 多行,因此我需要一种比手动执行此操作更快的方法。
答案 0 :(得分:3)
你可以这样做:
id <- seq_len(nrow(data))
new_values <- paste("pic_",id,sep = "")
data$Height <- new_values
答案 1 :(得分:3)
您也可以使用以下解决方案:
library(dplyr)
library(stringr)
df %>%
mutate(across(Height, ~ str_c("pic_", str_pad(row_number(), 5, "left", "0"))))
Temperature Height
1 32 pic_00001
2 31 pic_00002
3 33 pic_00003
答案 2 :(得分:3)
要实现最终输出(来自 monjeanjean 的原创,我还不能评论,哈哈):
id <- seq_len(nrow(data))
new_values <- paste("pic_",formatC(x,width=5,flag="0",format="fg"),sep = "")
data$Height <- new_values
答案 3 :(得分:3)
您可以使用# create the example used by the OP
dat <- data.frame(Temperature = 31:33,
Height = c(157, 159, 139))
# use sprintf along with seq_len
dat$Height <- sprintf("pic_%05d", seq_len(NROW(dat)))
# show the result
dat
#R> Temperature Height
#R> 1 31 pic_00001
#R> 2 32 pic_00002
#R> 3 33 pic_00003
:
05d
如果您想要更多前导零,您可以更改 07d
。例如。 sprintf
将给出一个七位数的序列。 void foo(){
struct {
char a[4];
char b[16];
char *p;
} s;
scanf("%s", s.p);
printf("flag: %s", s.p);
}
int main(){
foo();
}
的手册页包含更多详细信息。