英文:
How to paste two strings with quotation signs?
问题
以下是翻译后的内容:
Let's say I have two columns in a dataframe, the first shows the codes of items; whereas the second shows the description, I want to construct a third that concatenates first two columns and displays in a format such as "1" = "soap" for the first row, and so on. Is it possible? Thanks in advance.
我有一个数据框中的两列,第一列显示物品的编码,而第二列显示描述,我想构建一个第三列,将前两列连接起来,以类似于第一行的格式显示,例如"1" = "soap",依此类推。这是否可能?提前感谢。
I have tried something like c("abc", "def") and different variations of that format, none worked.
我尝试了类似c("abc", "def")和不同的格式变化,但都没有成功。
英文:
Let's say I have two columns in a dataframe, the first shows the codes of items; whereas the second shows the description, I want to construct a third that concatenates first two columns and displays in a format such as "1" = "soap" for the first row, and so on. Is it possible? Thanks in advance
I have tried something like c(""abc"", ""def"") and different variations of that format, none worked.
答案1
得分: 0
We may use sprintf
in Reduce
.
res <- Reduce(\(x, y) sprintf('%s'='%s', x, y), dat[c(1, 2)])
res
# [1] '"1"="a"' '"2"="b"' '"3"="c"' '"4"="d"' '"5"="e"' '"6"="f"'
Looks weird, but just because internal storage method is shown. See if we `cat` it:
cat(res)
# "1"="a" "2"="b" "3"="c" "4"="d" "5"="e" "6"="f"
Data:
dat <- data.frame(a=1:6, b=letters[1:6], x=runif(6))
英文:
We may use sprintf
in Reduce
.
res <- Reduce(\(x, y) sprintf('"%s"="%s"', x, y), dat[c(1, 2)])
res
# [1] "\"1\"=\"a\"" "\"2\"=\"b\"" "\"3\"=\"c\"" "\"4\"=\"d\"" "\"5\"=\"e\"" "\"6\"=\"f\""
Looks weird, but just because internal storage method is shown. See if we cat
it:
cat(res)
# "1"="a" "2"="b" "3"="c" "4"="d" "5"="e" "6"="f"
Data:
dat <- data.frame(a=1:6, b=letters[1:6], x=runif(6))
答案2
得分: 0
transform(dat, x=sprintf('"%s"="%s"', a, b))
a b x
1 1 a "1"="a"
2 2 b "2"="b"
3 3 c "3"="c"
4 4 d "4"="d"
5 5 e "5"="e"
6 6 f "6"="f"
transform(dat, x = paste(shQuote(a), shQuote(b), sep='='))
a b x
1 1 a "1"="a"
2 2 b "2"="b"
3 3 c "3"="c"
4 4 d "4"="d"
5 5 e "5"="e"
6 6 f "6"="f"
英文:
transform(dat, x=sprintf('"%s"="%s"', a, b))
a b x
1 1 a "1"="a"
2 2 b "2"="b"
3 3 c "3"="c"
4 4 d "4"="d"
5 5 e "5"="e"
6 6 f "6"="f"
transform(dat, x = paste(shQuote(a), shQuote(b), sep='='))
a b x
1 1 a "1"="a"
2 2 b "2"="b"
3 3 c "3"="c"
4 4 d "4"="d"
5 5 e "5"="e"
6 6 f "6"="f"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论